Avoiding instanceof in Java

You might be interested in this entry from Steve Yegge’s Amazon blog: “when polymorphism fails”. Essentially he’s addressing cases like this, when polymorphism causes more trouble than it solves.

The issue is that to use polymorphism you have to make the logic of “handle” part of each ‘switching’ class – i.e. Integer etc. in this case. Clearly this is not practical. Sometimes it isn’t even logically the right place to put the code. He recommends the ‘instanceof’ approach as being the lesser of several evils.

As with all cases where you are forced to write smelly code, keep it buttoned up in one method (or at most one class) so that the smell doesn’t leak out.

Leave a Comment