Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 475
aioobe Avatar asked May 01 '10 16:05

aioobe


People also ask

Is it bad practice to use Instanceof?

Probably most of you have already heard that using “instanceof” is a code smell and it is considered as a bad practice. While there is nothing wrong in it and may be required at certain times, but the good design would avoid having to use this keyword.

What can I use instead of Instanceof?

Having a chain of "instanceof" operations is considered a "code smell". The standard answer is "use polymorphism".

How does Instanceof work in Java?

The instanceof operator in Java is used to check whether an object is an instance of a particular class or not. objectName instanceOf className; Here, if objectName is an instance of className , the operator returns true . Otherwise, it returns false .

How do you stop an instance of Java?

The primary alternative to using instanceof is polymorphism. Rather then ask which type of object you have at the current position you tell the object, whatever it is, to do what you want done. If both objects know how to do that then this works fine, even if they do it differently.


1 Answers

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.

like image 173
Alexander Pogrebnyak Avatar answered Sep 28 '22 18:09

Alexander Pogrebnyak