Is instanceof considered bad practice? If so, under what circumstances is instanceof still preferable?

JavaInstanceof

Java Problem Overview


Over the years, I've tried to avoid instanceof whenever possible. Using polymorphism or the visitor pattern where applicable. I suppose it simply eases maintenance in some situations... Are there any other drawbacks that one should be aware of?

I do however see it here and there in the Java libraries so I suppose it has its place? Under what circumstances is it preferable? Is it ever unavoidable?

Java Solutions


Solution 1 - Java

It's definitely has its place in a stock implementation of equals. E.g.

public boolean equals ( Object o )
{
  if ( this == o )
  {
     return true;
  }

  if ( ! (o instanceof MyClass) )
  {
    return false;
  }
  
  // Compare fields
  ...
}

One neat thing to know about instanceof is that its LHS can be null and in that case the expression evaluates to false.

Solution 2 - Java

I can imagine some cases, for example you have some objects of a library, which you can't extend (or it would be inconvenient to do so), perhaps mixed with some objects of your, all with same base class, together in a collection.
I suppose that in such case, using instanceof to distinguish some processing on these objects might be useful.

Idem in some maintenance of legacy code where you cannot inject some new behavior in lot of old classes just to add a new little feature or some bug fix...

Solution 3 - Java

I think that when you absolutely need to know the type of an object, instanceof is the best option available.

A bad practice would be to have a lot of instanceofs, one next to the other, and according to them call different methods of the objects (of course casting). This would probably reflect that the hierarchy needs rethinking and probably refactoring.

Solution 4 - Java

When you are inside a pure OO model, then instanceof is definitely a code smell.

If, however, you are not using a 100% OO model or you need to inject stuff into it from the outside, then instanceof or equivalents (isXXX(), getType(), ...) can have its uses.

The general "rule" would be to avoid it whenever possible, especially when you control the type hierarchy and can use subtype polymorphism for example. The idea is not to ask the object what type it is and do something with it, but rather to ask the object directly or indirectly via a Visitor (essentially double polymorphism) to perform some action.

Solution 5 - Java

It can well be used as a sanity check before casting; in addition to checking that your object is of right type, it also does check that it's not null.

if (o instanceof MyThing) {
    ((MyThing) o).doSomething(); // This is now guaranteed to work.
} else {
    // Do something else, but don't crash onto ClassCast- or NullPointerException.
}

Solution 6 - Java

I agree it can have a bad smell. Lots of instanceof, expecially in a chained together if block, smells of bad.

Sometimes it can behave in ways you would not expect... Something I had happen once:

Class B extends A
Class C extends A

B b = new B();
C c = new C();

b instanceof B -> true
b instanceof C -> true
c instanceof C -> true
c instanceof B -> true

(in my case this happened due to hibernate making proxy objects.... but just a case where code dpending on instanceof is risky)

Solution 7 - Java

How about in the case of a creation factory? e.g.

public static Cage createCage(Animal animal) {
  if (animal instanceof Dog)
    return new DogHouse();
  else if (animal instanceof Lion)
    return new SteelCage();
  else if (animal instanceof Chicken)
    return new ChickenWiredCage();
  else if (animal instanceof AlienPreditor)
    return new ForceFieldCage();
  ...
  else
    return new GenericCage();
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionaioobeView Question on Stackoverflow
Solution 1 - JavaAlexander PogrebnyakView Answer on Stackoverflow
Solution 2 - JavaPhiLhoView Answer on Stackoverflow
Solution 3 - JavaDaniel DolzView Answer on Stackoverflow
Solution 4 - JavaeljensoView Answer on Stackoverflow
Solution 5 - JavaJoonas PulakkaView Answer on Stackoverflow
Solution 6 - JavabwawokView Answer on Stackoverflow
Solution 7 - JavaThorView Answer on Stackoverflow