Is using the instanceof
keyword against the essence of object oriented programming
?
I mean is it a bad programming practice?
I read somewhere that us
Usage of instanceof
is discouraged when same effect can be achieved via virtual methods, like in example of thomson_matt.
However, it's necessary to use instanceof
in some circumstances. For example, when your code gets Object from external source, say, network or third-party API which returns Object
, and you must decide what is the type of this Object and act appropriately.
Generally speaking yes. It's best to keep all code that depends on being a specific class within that class, and using instanceof
generally means that you've put some code outside that class.
Look at this very simple example:
public class Animal
{
}
public class Dog extends Animal
{
}
public class Cat extends Animal
{
}
public class SomeOtherClass
{
public abstract String speak(Animal a)
{
String word = "";
if (a instanceof Dog)
{
word = "woof";
}
else if (a instanceof Cat)
{
word = "miaow";
}
return word;
}
}
Ideally, we'd like all of the behaviour that's specific to dogs to be contained in the Dog class, rather than spread around our program. We can change that by rewriting our program like this:
public abstract class Animal
{
public String speak();
}
public class Dog extends Animal
{
public String speak()
{
return "woof";
}
}
public class Cat extends Animal
{
public String speak()
{
return "miaow";
}
}
public class SomeOtherClass
{
public String speak(Animal a)
{
return a.speak();
}
}
We've specified that an Animal
has to have a speak
method. Now SomeOtherClass
doesn't need to know the particular details of each type of animal - it can hand that off to the subclass of Animal
.