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:
- 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