Is instanceof considered bad practice? If so, under what circumstances is instanceof still preferable?
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
.
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 instanceof
s, 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.
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...