Composition Over Inheritance

By Karol Bocian | February 27, 2020

Composition Over Inheritance

The principle says, that we should prefer composition (class A uses class B) than inheritance. When using inheritance, remember not to break the Liskov Substitution Principle.

The principle does not say that we should completely reject inheritance.

Example:

We have a Worker and a Manager.

Inheritance: Both classes have names and surname. They can inherit an Employee class.

Composition: Both classes calculate salary. A better solution is injected salary calculator into Worker and Manager.

Advantages

  • Less dependency between classes.
  • Classes are smaller (and have less responsibility).
  • Easier comply SOLID principles.
  • Easier testing.

Disadvantages

  • Sometimes inheritance is better.

All posts from mini project: Learn SOLID and OOP principles:

Sources

Main image

Materials