DEV Community

Discussion on: Why composition is superior to inheritance as a way of sharing code

Collapse
 
danderson profile image
Dale Anderson

Inheritance creates very strong coupling between base classes and derived classes. It's very difficult to break this coupling, i.e. you become somewhat locked in to your original conception of how your system is structured. In long lived systems, this inevitably changes.

In my experience, the very dire consequence of this is that as your system grows in size and complexity, base classes tend to accumulate many aspects that may or may not apply to all of its derived classes. It's extremely difficult to reason about systems with base classes that are over several hundred (thousand?) lines long.

Composition is a far more flexible approach that allows a more fine grained approach to decomposing the various elements of your system.

OOP looks great when you consider the simple examples that they teach in computer science 101, like cats being mammals that are in turn all animals, or a teacher and a student being specializations of a person. However, it is extremely difficult to scale to today's large size systems, mostly due to the strong coupling I mentioned.