Composition over inheritance, and interfaces
Composition means building a class out of other objects it has ('has-a'), instead of inheriting from a parent ('is-a').
Why it matters
Inheritance looks like free reuse, but every subclass is tied to its parent's details. With several independent features, the number of subclasses explodes.
The idea
Inheritance ties a child class closely to its parent's internals, so changes ripple down and deep trees get rigid. Composition plugs behaviour in through small objects behind interfaces, so you can swap them at runtime and test each alone. Rule of thumb: inherit for a true 'is-a' with shared behaviour; otherwise, compose.
A phone with a replaceable camera module, compared with a phone whose camera is moulded into the case. Upgrading the module is easy; re-moulding the case isn't.
Phone modules have sockets designed in advance. In code you still have to choose good interfaces, and composing everything everywhere can create a maze of tiny objects.
How it works
- With inheritance, 3 kinds of flying × 3 kinds of sound = 9 subclasses, and every new kind multiplies them again.
- With composition, a Duck simply holds a flyer object and a quacker object.
- Each behaviour is a small class implementing a tiny interface: fly() or quack().
- You build a duck by choosing its parts: Duck(Wings(), Quack()) or Duck(NoFly(), Squeak()).
- You can even swap a part while the program runs, and test each part on its own.
Example
Instead of Duck → FlyingDuck → QuackingFlyingDuck classes, a Duck has a flying behaviour and a quacking behaviour. A rubber duck gets NoFly and Squeak.
Key points
- If one thing "is a" kind of another, inheritance may fit. If it "has a" part, use composition.
- Composition lets you change behaviour at runtime and test with fakes.
- Program to an interface, not to an implementation: depend on what a part does, not on which class does it.
- Dependency injection: pass collaborators in; don't create them inside the class.
Common mistakes
- Using inheritance for 'has-a' relationships (a Car extends Engine).
- Creating collaborators inside the class instead of passing them in.
Not true: A Car class should extend Engine, because a car needs an engine.
In fact: A car has an engine; it is not a kind of engine. Use composition: the Car holds an Engine object and calls it.
In the interview
I prefer composition: a class holds small collaborator objects behind interfaces, and they're injected. It's more flexible than inheritance, easier to test, and avoids fragile class trees. I use inheritance only for a genuine 'is-a' with shared behaviour.
Part of Unit 5: Low-level design: OOP and SOLID in the free System Design course.