Skip to content

Composition

Medium — good to knowArchitecture

ELI5 — The Vibe Check

Composition means building complex things by combining simple ones, rather than inheriting from a parent class. Instead of 'Car extends Vehicle extends Machine', you have 'Car has an Engine, has Wheels, has a Stereo'. Lego bricks, not Russian nesting dolls.

Real Talk

Composition is an OOP design approach where complex behavior is achieved by combining objects rather than through inheritance chains. 'Favor composition over inheritance' (GoF) promotes flexibility since composed objects can be swapped at runtime and avoids the fragile base class problem.

Show Me The Code

// Composition over inheritance
class Logger { log(msg: string) { console.log(msg); } }
class Validator { validate(data: unknown) { /* ... */ } }

class UserService {
  private logger = new Logger();
  private validator = new Validator();
  // uses both without inheriting from either
}

When You'll Hear This

"Prefer composition over inheritance here." / "Composition gives us more flexibility than a deep inheritance tree."

Made with passive-aggressive love by manoga.digital. Powered by Claude.