Composition over Inheritance

Inheritance

In simple words, Inheritance is, when a child class inherits from a parent class, the child acquires all behaviors from the parent. Inheritance will make a class hierarchy — you can imagine it as a tree of classes.

Composition

Composition is in contrast to inheritance, it enables the creation of complex types by combining objects (components) of other types, rather than inheriting from a base or parent class. To put it simply, composition contains instances of other classes that implement the desired functionality. We can imagine composition as playing with Legos, while components are the Lego bricks.

Inheritance vs. Composition

The main difference between inheritance and composition is in the relationship between objects.

  • Inheritance: “is a.” E.g. The car is a vehicle.

  • Composition: “has a.” E.g. The car has a steering wheel.

Inheritance is known as the tightest form of coupling in object-oriented programming. Changing a base class can cause unwanted side effects on its subclasses or even all over the codebase.

Composition is a far looser coupling. Combining with Dependency Injection (here), it brings more flexibility and also allows us to change runtime behavior.

When building a class combining various components, it’s more natural to use composition than to try to find commonality between them and create a class tree.

This approach accommodates future requirement changes, that may require a complete restructuring of the class tree in the inheritance approach, more easily. We can simply add a new component to the composited class rather than modifying the superclass to adapt changes.

They’re different in purpose too.

  • Inheritance: To design a class on what it is.

  • Composition: To design a class on what it does.

Inheritance should only be used when:

  1. Both classes are in the same logical domain

  2. The subclass is a proper subtype of the superclass

  3. The superclass’s implementation is necessary or appropriate for the subclass

  4. The enhancements made by the subclass are primarily additive.

Example of using inheritance: client errors classes inherited from the common error, each class has its overridden message.

Last updated

Was this helpful?