Why not use instanceof operator in OOP design?

Viewed 9762

It has been repeatedly said that the instanceof operator should not be used except in the equals() method, otherwise it's a bad OOP design.

Some wrote that this is a heavy operation, but it seems that, at least java, handles it pretty well (even more efficiently than Object.toString() comparison).

Can someone please explain, or direct me to some article which explains why is it a bad design?

Consider this:

Class Man{
  doThingsWithAnimals(List<Animal> animals){
    for(Animal animal : animals){
      if(animal instanceOf Fish){
        eatIt(animal);
      }
      else if(animal instanceof Dog){
        playWithIt(animal);
      }
    }
  }
  ...
}

The decision of what to do with the Animal, is up to the Man. Man's desires can also change occasionally, deciding to eat the Dog, and play with the Fish, while the Animals don't change.

If you think the instanceof operator is not the correct OOP design here, please tell how would you do it without the instanceof, and why?

4 Answers

using instance of is a bad practise because in the OOP there is no need to check what the class is, if the method is compatible you should to be able to call it with such arguments, otherwise design is spoiled, flawed, but it exist the same way as goto in C and C++, I think sometimes it might be easier to integrate a bad code using instance of but if you make your own proper code avoid it so basically this is about of programming style what is good and what is bad, when and why in some curcumstances bad style is used, because sometimes the code quality is secondary, perhaps sometimes the goal is to make the code not easy to understand by others so that would be the way to do it

Related