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?
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.
Having a chain of "instanceof" operations is considered a "code smell". The standard answer is "use polymorphism".
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 .
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With