Favor Composition Over Inheritance
What you'll learn: Why assembling objects from smaller, reusable parts is often better than building tall inheritance trees.
The Core Idea
When designing software, you often need to share or combine functionality. Inheritance means creating a parent-child relationship where the child "is-a" type of parent and inherits all its behaviors. Composition means building objects by combining smaller, independent components—essentially "has-a" relationships.
Favoring composition means preferring to build functionality by assembling objects that delegate to other objects, rather than extending class hierarchies.
Why Composition Wins
Imagine building vehicles. With inheritance, you might create:
Vehicle→Car→SportsCar→ConvertibleSportsCar
This quickly becomes rigid. What if you need a convertible truck? You'd need parallel hierarchies, duplicating logic.
With composition, you build vehicles from parts:
- A vehicle has an engine
- A vehicle has a roof (hardtop or convertible)
- A vehicle has wheels
Now any vehicle can mix and match components. Want a convertible truck? Just compose it with a truck body and convertible roof component.
Key Benefits
Flexibility: Swap components at runtime without changing class hierarchies.
Reusability: Small, focused components work across many contexts.
Avoiding fragility: Deep inheritance chains break easily when parent classes change.
Clearer relationships: "Has-a" is often more honest than forcing "is-a" relationships.
This ties directly back to Program to an Interface, Not an Implementation—your composed objects depend on interfaces, not concrete parent classes.
Key Takeaway: Build objects by combining smaller, independent parts rather than creating complex inheritance hierarchies—you gain flexibility, reusability, and simpler designs.