Composition over Inheritance
Composition over inheritance advises building behavior by containing other objects rather than inheriting, avoiding fragile base classes and deep inheritance chains.
Purpose
Design flexible, maintainable object relationships and avoid the coupling and fragility of inheritance.
Mechanism
A has-a relationship (composition) is preferred over an is-a relationship (inheritance). Composition allows components to be swapped at runtime, while inheritance is fixed at compile time. The strategy and decorator patterns use composition. Interfaces plus composition achieve polymorphism without inheritance.
Use cases
- Object-oriented design
- Design patterns
- Code architecture