Java – Avoiding instanceof in Java

java

I am trying to check if my array A has an instance of object B at the current position, since it is an array that can contain two types of objects (B and C). I do not want to use instanceof, so I'm wondering what other alternatives I have?

if(A[i] instanceof B)

Best Answer

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. The principle at work here is called Tell, don't ask.

If the language you're using doesn't have duck typing you will need types B and C to both explicitly implement the same interface or abstract type that has the method you want to call. This would mean that your array is homogeneous. It's when it's heterogeneous that you're left with no idea if you can call the method safely until you ask.

If you're working in a code base that uses an object oriented paradigm people will get very irritated to see use of instanceof. Not so much if you're in a procedural paradigm.

That isn't to say any one paradigm is always right. But when in Rome...


An oft used example:

At the pet show you array your lovely pets before your audience. To show how well trained they are you say to each, "Speak!"

Your duck quacks.

Your dog barks.

Your cat looks at you funny and then ignores you.

Your pet rock rips a hole in the fabric of reality because the designers of your reality forgot to give rocks any kind of speaking function.

The rock is the one that would put your array in the heterogeneous category. Keep the rocks out of your array and you can avoid instanceof.