
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:
- SOLID
- SOLID exercises
- S like Single responsibility principle
- SOLID exercises — Kata
- O as Open-closed principle
- L jak Liskov Substitution Principle
- Interface segregation principle
- KISS — Keep it simple, stupid
- DRY — Don’t repeat yourself
- Dependency inversion principle
- SLAP — Single Level of Abstraction Principle
- Composition Over Inheritance
- Encapsulate what changes
- Lod — Law of Demeter
- ES as Exercises of Single responsibility principle
- EO as Exercises of Open/closed principle
- EL as Exercises of Liskov Substitution Principle
- EI as Eexrcises of Interface segregation principle
- ES as Exercises of Dependency Inversion Principle
- Object-oriented programming
- OOP — Object-Oriented Programming — Advice
- OOP — Object Oriented Programming
Sources
Main image
Materials
- https://devcave.pl/notatnik-juniora/zasady-projektowania-kodu#composition-over-inheritance
- https://blog.helion.pl/dziedziczenie-vs-kompozycja/
- https://sarvendev.com/2017/10/kompozycja-ponad-dziedziczenie/
- https://javarevisited.blogspot.com/2013/06/why-favor-composition-over-inheritance-java-oops-design.html
- https://en.wikipedia.org/wiki/Composition_over_inheritance
Sorry, there was a YouTube error.