Polymorphism – Handling Methods Added for Subtypes

design-patternsobject-orientedpolymorphismsubtypes

When you use the concept of polymorphism you create a class hierarchy and using parents reference you call the interface functions without knowing which specific type has the object. This is great. Example:

You have collection of animals and you call on all animals function eat and you don't care if it is a dog eating or a cat. But in the same class hierarchy you have animals that have additional – other than inherited and implemented from class Animal, e.g. makeEggs, getBackFromTheFreezedState and so on. So in some cases in you function you might want to know the specific type to call additional behaviours.

For example, in case it is morning time and if it is just an animal then you call eat, otherwise if it is a human, then call first washHands, getDressed and only then call eat. How to handle this cases? Polymorphism dies. You need to find out the type of the object, which sounds like a code smell. Is there a common approach to handle this cases?

Best Answer

Depends. Unfortunately there is no generic solution. Think about your requirements and try to figure out what these things should do.

For example, you said in the morning different animals do different stuff. How about you introduce a method getUp() or prepareForDay() or something like that. Then you can continue with polymorphism and let each animal execute its morning routine.

If you want to differentiate among animals, then you should not store them indiscriminately in a list.

If nothing else works, then you could try the Visitor Pattern, which is kind-of a hack to allow for kind-of a dynamic dispatching where you can submit a visitor that will receive type-exact callbacks from animals. I would stress however that this should be a last resort if everything else fails.