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
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
.