Donald Barre
Donald A. Barre
Inheritance Hell
I have seen inheritance misused over and over in the course of my career. Let's look at two different misuses.
First, inheritance is fundamentally an "is-a" relationship between two class. For example, let's say we have an Vehicle class and a Car class. A Car is a Vehicle. Thus, our Car class can be a subclass of Vehicle. Along with domain objects, inheritance is also used for services, e.g. the CarService is a subclass of the VehicleService. This is all fine and good.
Unfortunately, I've seen this violated many times. To avoid referencing actual production code, I'll just do something similar to what I've seen. Let's say we have a CatService. It's got a meow() method along with some other functionality that has to do with the pet owner. At a later point, we need a DogService. It also needs the same pet owner functionality. Normally this would call for some refactoring. But I've seen developers cheat by simply make the DogService a subclass of the CatService. That is a clear violation. Of course, we then hope and pray that no one calls the meow() function on any of the dog instances.
The second misuse is the overuse of multilevel inheritance. Imagine we have Class A which is derived from Class B which is derived from Class C which is derived from Class D which is derived from Class E which is derived from Class F. That's only six levels. I've seen systems with ten or more levels of inheritance. It becomes difficult to understand what each level is responsible for. To make it even more confusing, I have seen hierarchies like these where the child classes often override the behavior of their parent classes. At this point, the logic is so spread out that it is next to impossible to understand.
My recommendations for inheritance are:
  • If it isn't an "is-a" relationship, don't use inheritance.
  • Refactor when necessary.
  • Try to keep the inheritance levels to three or less. Alarm bells should go off once you go past four.
  • Use Composition to help avoid the explosion of levels.
© Donald A. Barre. All rights reserved.