Composition over Inheritance
phrase
say it: “kom-puh-ZISH-un OH-ver in-HAIR-ih-tuns” /ˌkɑmpəˈzɪʃən ˈoʊvər ɪnˈhɛrɪtəns/
The advice to build an object from parts it holds, instead of from a family tree of subclasses, especially when options combine.
What is Composition over Inheritance?
Composition over inheritance is the advice to build behavior by combining small objects rather than stacking up deep class hierarchies. It keeps code flexible because parts can be swapped.
// Instead of FlyingSwimmingDuck : SwimmingDuck : Duck ...
public class Duck
{
private readonly IFlyBehavior fly;
private readonly ISwimBehavior swim;
public Duck(IFlyBehavior fly, ISwimBehavior swim) { this.fly = fly; this.swim = swim; }
}
In a sentence
- “Following composition over inheritance, a menu item now holds a list of extras instead of a subclass for each mix.”
Level: Journeyman · More OOP terms at this level
Updated