Composition
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."
Related Terms
Dependency Injection
Instead of your UserService creating its own DatabaseConnection (tight coupling), you pass the database in from outside: new UserService(db).
Design Pattern
Design patterns are like recipe cards for solving common coding problems.
Inheritance
Inheritance lets a class take on all the properties and behaviors of another class.
SOLID (SOLID)
SOLID is five rules for writing code that doesn't turn into a nightmare over time. Each letter stands for a different rule.