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.


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.


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


  • Sometimes inheritance is better.

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


Main image


Leave a Reply

Your email address will not be published. Required fields are marked *