Composition
Prefer has-a over is-a — building systems from collaborating parts.
18 minLevel 14 of 20
Has-a over is-a
Composition builds behavior by combining objects. A Car has-an Engine — it is not an Engine. Nest services compose repositories, mailers, and gateways via DI.
Has-a
class Engine { start() { return "vroom"; } }
class Car {
constructor(private engine: Engine) {}
start() { return this.engine.start(); }
}
console.log(new Car(new Engine()).start());Compare with inheritance
Inheritance couples you to a parent forever. Composition lets you swap parts. Open the Composition simulator for a side-by-side.
Swappable parts
interface Engine { start(): string; }
class GasEngine implements Engine { start() { return "gas"; } }
class ElectricEngine implements Engine { start() { return "electric"; } }
class Car {
constructor(private engine: Engine) {}
start() { return this.engine.start(); }
}
console.log(new Car(new GasEngine()).start());
console.log(new Car(new ElectricEngine()).start());Nest composition root
Modules are composition roots for a feature. Providers are the parts; the container assembles the machine.
Assembled graph
class Repo { all() { return [1, 2]; } }
class Service { constructor(private r: Repo) {} list() { return this.r.all(); } }
class Controller { constructor(private s: Service) {} get() { return this.s.list(); } }
console.log(new Controller(new Service(new Repo())).get());Check your understanding
5 questionsQuestion 1 of 5
Score: 0
Multiple choice