Why not use instanceof operator in OOP design?

instanceof, oop

Solution

`instanceof` simply breaks the Open/Close principle. and/or Liskov substitution principle

If we are not enough abstract because of `instanceof` usage, each time a new subclass makes an entrance, the main code gathering the logic of the application might be updated. This is clearly not what we want, since it could potentially break the existing code and reduce its reusability.

Therefore, a good usage of polymorphism should be preferred over the basic use of conditional.

Problem

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?

Original source