1. Concept library
  2. JavaScript & TypeScript
  3. Module 9: Classes and composition

Concept

Composition over inheritance

Build behaviour by combining small objects and functions rather than deep class hierarchies. Composition keeps each piece testable and avoids the fragile base class problem.

What a session covers

The tutor works through these with you, in conversation and code. A session ends when you have shown them, not when a video does.

  1. Explain the fragile base class problem in your own words
  2. Rewrite a small inheritance hierarchy as composed objects and functions
  3. Spot a subclass created to reuse a single method

In practice

A few lines that show Composition over inheritance doing its job.

TypeScript
type Logger = { log(message: string): void };
type Clock = { now(): Date };

class OrderService {
  constructor(private readonly logger: Logger, private readonly clock: Clock) {}

  place(order: Order) {
    this.logger.log("placed at " + this.clock.now().toISOString());
  }
}

new OrderService(console, { now: () => new Date() });

The common mistake

Watch for

Subclassing to reuse a single method, which drags in the whole parent and ties the two classes together. Pass the behaviour in as a dependency instead.

What to know first

Your roadmap puts these before Composition over inheritance, unless you already know them.

How it stays learned

Once a session shows you understand Composition over inheritance, it comes back for review. Each review takes a minute and tells the memory model how well you still know it.

  1. Day 3First recall, while it is fresh
  2. Day 7Second, a week on
  3. Day 18Last, when it has settled
Previous in the module← Implementing interfaces