Composition Over Inheritance
Build objects from smaller objects instead of deep hierarchies, delegate work to collaborators, and avoid the class explosion that inheritance alone causes.
Welcome back!
Step 1 of 12Learn
The class explosion
A notification system starts simply: EmailNotifier. Then the team needs SMS, so SmsNotifier. Then some notifications must be retried on failure: RetryingEmailNotifier, RetryingSmsNotifier. Then some must be logged: LoggingEmailNotifier, LoggingRetryingEmailNotifier, LoggingRetryingSmsNotifier...
Each new channel or feature multiplies the number of classes. With 3 channels and 3 optional features that can be combined freely, inheritance needs a subclass for every combination: 3 × 2 × 2 × 2 = 24 classes. Adding a fourth channel adds 8 more.
Composition builds behavior by combining objects instead. A notifier has a channel and has a list of features:
class Notifier {
constructor(channel, { retries = 0, logger = null } = {}) {
this.channel = channel; // any object with send(to, message)
this.retries = retries;
this.logger = logger;
}
notify(to, message) {
for (let attempt = 0; attempt <= this.retries; attempt++) {
try {
this.channel.send(to, message); // delegate the real work
this.logger?.log('sent to ' + to);
return true;
} catch (e) { this.logger?.log('failed: ' + e.message); }
}
return false;
}
}
const n = new Notifier(new SmsChannel(), { retries: 2, logger: console });Now there are 3 channel classes and one Notifier. Any combination is a constructor call, and a fourth channel is one new class. The notifier delegates sending to its channel object: it forwards the call instead of doing the work itself.
Step 2 of 12Try the calculator
Inheritance vs. composition: how many classes?
Each feature is optional and can be combined with the others. Inheritance needs one class per channel for every on/off combination of features; composition needs one class per channel plus one per feature plus the object that ties them together.
- Classes with inheritance only
- 24
- Classes with composition
- 7
Step 3 of 12Practice · Work it out
A reporting tool supports 4 output formats (PDF, CSV, HTML, Excel) and 3 optional features that can be combined freely (compression, encryption, watermark). How many classes would a pure inheritance design need to cover every combination?
Step 4 of 12Learn
Delegation and the "has-a" toolkit
Composition relies on delegation: an object keeps a reference to a helper and forwards work to it. You saw a stack built badly with extends Array. Here it is with composition:
class Stack {
#items = [];
push(x) { this.#items.push(x); }
pop() { return this.#items.pop(); }
peek() { return this.#items[this.#items.length - 1]; }
get size() { return this.#items.length; }
}The stack has an array and exposes only the operations a stack should allow. Callers can't splice into the middle, because the array is private.
Composition brings several practical advantages:
- Pick only what you need. You expose a few methods instead of inheriting a parent's whole interface.
- Change at run time. A game character can swap its
weaponobject mid-game; a class's parent is fixed forever. - Loose coupling. The stack depends only on the array's public methods, not on the internal details of a parent class.
- Easy testing. Pass a fake channel into the notifier and check what it was asked to send, without sending real messages.
The cost is a little more code: forwarding methods such as push must be written by hand. That's usually a fair trade for the control you gain.
Step 5 of 12Practice · What would you do?
What would you do?
In an RPG, Character has subclasses Warrior, Mage and Archer. Designers now want a character to change weapons during play: a warrior who picks up a bow should attack like an archer. What design handles this best?
Step 6 of 12Practice · Diagram
A composed Notifier
Which part would you replace with a fake to test without sending real messages?
Tap the shape that answers the question, then press Check.
- Notifier
- channel
Any object with send(to, message): email, SMS, a test fake.
- retries
A number, not a subclass.
- logger (optional)
Any object with log(), or none.
- notify()
Loops, delegates to channel.send(), logs results.
Step 7 of 12Learn
When inheritance is still the right call
"Composition over inheritance" is a preference, not a ban. Inheritance remains a good fit when:
- the relationship is a true, permanent is-a that passes the Liskov test;
- the parent is designed for extension, with documented methods meant to be overridden, as in UI frameworks where you extend a base component;
- subclasses share substantial code and state, and the hierarchy stays shallow.
Composition fits better when:
- you want to reuse behavior from something that isn't really a parent ("has-a", "uses-a");
- behavior must vary independently along several dimensions, like channel and retry policy;
- behavior must change at run time;
- the parent class belongs to someone else and might change without warning.
Many experienced designers start with composition and introduce inheritance only when a clear is-a hierarchy appears. Some modern languages lean the same way: Go has no class inheritance at all and builds everything from composition and interfaces, while Rust uses traits instead of class hierarchies.
Step 8 of 12Practice · Sort into groups
For each situation, which approach fits better?
Tap an item, then tap its group (or drag it there).
Step 9 of 12Learn
Mixins and traits: sharing behavior sideways
Sometimes several unrelated classes need the same small piece of behavior, such as serializing to JSON or emitting events, and neither inheritance nor a separate collaborator object feels right. Many languages offer a middle path.
- Mixins copy a set of methods into a class. In JavaScript you can write
Object.assign(User.prototype, serializable), or build a mixin as a function that takes a class and returns a subclass with extra methods. Python developers write mixin classes and combine them with multiple inheritance, as inclass Report(JsonMixin, Base). - Traits (Rust, Scala, PHP) and default interface methods (Java, C#, Kotlin) let an interface carry reusable method bodies that classes pick up when they implement it.
These tools sit between inheritance and composition: the behavior becomes part of the class, but without spending the single parent slot and without a deep hierarchy.
Use them sparingly. Mixins that rely on each other's fields, or two mixins that define the same method name, recreate the fragile-base-class problem in a less visible form. If the behavior needs its own state and configuration, a separate collaborator object, passed in and delegated to, is usually clearer.
Step 10 of 12Practice · True or false
Mixins let unrelated classes share a set of methods without placing them all under one common parent class.
Step 11 of 12Flashcards
Composition vocabulary
Tap a card to flip it.
Step 12 of 12Practice · Choose one
What is the main reason composition makes the Notifier easier to test than an inheritance-based design?
Lesson complete!