Composition vs Inheritance: Why Composition Usually Wins
Inheritance models is-a relationships; composition models has-a. Learn why composition is more flexible, and when inheritance is still right.
By Velloreth
Two ways to reuse code
Both inheritance and composition let you avoid duplicating code. They differ in how.
Inheritance shares code by extending a parent class. The child inherits the parent’s methods and fields.
class Animal {
eat() { console.log('eating'); }
}
class Dog extends Animal {
bark() { console.log('woof'); }
}
const d = new Dog();
d.eat(); // inherited
d.bark(); // own
Composition shares code by holding objects and delegating to them.
class Eater {
eat() { console.log('eating'); }
}
class Dog {
private eater = new Eater();
eat() { this.eater.eat(); } // delegate
bark() { console.log('woof'); }
}
Both give Dog an eat method. The difference is the relationship: inheritance says a Dog is an Animal; composition says a Dog has an Eater.
Why the distinction matters
The relationship is not just semantics. It determines how the code can change.
With inheritance, Dog is permanently an Animal. It inherits everything the parent has, including things it does not want. It cannot be an Animal and something else. And if Animal changes, Dog may break.
With composition, Dog holds an Eater. It can hold a different eater, hold several behaviours, or drop one. Nothing about Dog is committed to a hierarchy.
The fragile base class problem
This is the strongest argument against inheritance, and it is worth understanding concretely.
class Collection {
private items: string[] = [];
add(item: string) { this.items.push(item); }
addAll(items: string[]) {
for (const item of items) this.add(item); // calls add
}
get count() { return this.items.length; }
}
class UniqueCollection extends Collection {
add(item: string) {
if (!this.items.includes(item)) super.add(item);
}
}
This looks fine. UniqueCollection overrides add to prevent duplicates, and addAll calls add, so duplicates are prevented there too.
Now the base class changes:
class Collection {
addAll(items: string[]) {
this.items.push(...items); // no longer calls add
}
}
The optimisation is correct for Collection. But UniqueCollection silently stops deduplicating when addAll is used, because the base class no longer routes through add. Nothing fails to compile. The bug appears at runtime, in a subclass the author of the change may not know exists.
This is the fragile base class problem. The subclass depends on an implementation detail of the parent — that addAll calls add — which is not part of the contract and can change.
Composition avoids it entirely, because there is no parent to depend on.
The diamond problem
Inheritance also struggles when a type needs behaviour from two sources.
class Swimmer { swim() { /* ... */ } }
class Flyer { fly() { /* ... */ } }
// A duck can swim and fly — but which do we extend?
class Duck extends Swimmer { } // loses fly
Languages with single inheritance forbid the situation. Languages with multiple inheritance, like C++, allow it but introduce ambiguity when both parents share an ancestor.
Composition solves it directly:
class Duck {
private swimmer = new Swimmer();
private flyer = new Flyer();
swim() { this.swimmer.swim(); }
fly() { this.flyer.fly(); }
}
The duck has both capabilities, with no ambiguity and no hierarchy.
Composition in practice
The idiomatic form of composition is dependency injection: a class receives the objects it needs rather than creating or inheriting them.
interface Logger {
log(message: string): void;
}
interface Repository {
save(entity: User): Promise<void>;
}
class UserService {
constructor(
private logger: Logger,
private repository: Repository,
) {}
async createUser(data: UserData) {
this.logger.log(`Creating user ${data.email}`);
await this.repository.save({ ...data, id: generateId() });
}
}
UserService composes a logger and a repository. It can be tested with fakes, and either dependency can be swapped without touching the class.
Compare the inheritance version:
class UserService extends BaseService {
// inherits logging, but is now permanently a BaseService
// and cannot be tested without the real logger
}
The composition version is more code but far more flexible.
The strategy pattern
Composition’s flexibility shows most clearly when behaviour varies at runtime.
interface PricingStrategy {
calculate(base: number): number;
}
class RegularPricing implements PricingStrategy {
calculate(base: number) { return base; }
}
class PremiumPricing implements PricingStrategy {
calculate(base: number) { return base * 0.8; }
}
class Cart {
constructor(private pricing: PricingStrategy) {}
total(base: number) {
return this.pricing.calculate(base);
}
}
const cart = new Cart(new PremiumPricing());
// later, swap the strategy
cart.pricing = new RegularPricing();
With inheritance, the pricing behaviour would be fixed at class definition time. With composition, it is a value that can change.
When inheritance is right
Composition is the better default, but inheritance is not wrong. It fits when:
The relationship is genuinely is-a. A SavingsAccount is an Account. A Circle is a Shape. The subtype must be usable anywhere the supertype is, which is the Liskov substitution principle.
The shared behaviour is stable. If the base class is unlikely to change, the fragile base class problem does not bite.
The hierarchy is shallow. One or two levels are manageable. Five levels are not.
The language makes it natural. Some frameworks are built around inheritance — UI component trees, exception hierarchies, and many ORMs. Fighting the framework is worse than using its idiom.
You are extending a framework’s extension point. When a framework says “subclass this and override render”, that is the intended design.
The Liskov substitution principle
The test for whether inheritance is appropriate is whether the subtype can replace the supertype without breaking anything.
class Rectangle {
setWidth(w: number) { this.width = w; }
setHeight(h: number) { this.height = h; }
}
class Square extends Rectangle {
setWidth(w: number) { this.width = this.height = w; }
setHeight(h: number) { this.width = this.height = h; }
}
A Square is mathematically a Rectangle, but it is not substitutable: code that sets width and height independently gets the wrong area. This is the classic Liskov violation, and it shows that “is-a” in the real world does not always mean “is-a” in code.
The fix is composition: a Square has a side length; a Rectangle has a width and height. Neither extends the other.
Refactoring inheritance into composition
If you have an existing hierarchy that is causing trouble, the conversion is usually mechanical.
Start by identifying what the subclass actually uses from the parent. Often it is a small subset of the parent’s methods, and the rest is inherited baggage. Extract that subset into a separate class or a set of small classes.
Then replace the extends with a field, and delegate the methods the subclass needs:
// Before
class ReportService extends BaseService {
generate() {
this.log('generating'); // inherited
return this.buildReport();
}
}
// After
class ReportService {
constructor(private logger: Logger) {}
generate() {
this.logger.log('generating'); // composed
return this.buildReport();
}
}
The behaviour is identical. What changed is that ReportService no longer depends on BaseService’s implementation, and the logger is now visible in the constructor and replaceable in tests.
The conversion is worth doing when you notice any of these signals: a subclass that overrides a method only to disable it, a subclass that throws “not supported” for inherited methods, a base class change that breaks subclasses, or a hierarchy more than two levels deep. Each of those is a sign that the is-a relationship is not real, and composition would express the actual relationship more honestly.
Practical guidance
- Default to composition. Reach for inheritance only when the is-a relationship is genuine and the behaviour is stable.
- Keep hierarchies shallow — one level, two at most.
- Program to interfaces, and inject implementations.
- Watch for the fragile base class problem — if a subclass depends on how the parent implements something, the design is wrong.
- Check Liskov — if the subtype cannot replace the supertype, do not use inheritance.
- Use composition for varying behaviour and inheritance for stable structure.
- Do not fight the framework — if it is built on inheritance, use inheritance.
For the related concepts, see interfaces vs abstract classes and SOLID principles explained. For the practical patterns, design patterns for beginners and dependency injection without a framework.
Quotable summary
Inheritance models an is-a relationship and shares implementation through a parent class, while composition models has-a and shares behaviour by holding objects and delegating to them. Composition is more flexible because behaviour can be swapped at runtime, and it avoids the fragile base class problem, where a change to a parent silently breaks subclasses that depended on its implementation details. The diamond problem, where a type needs behaviour from two parents, is solved by composition and by interfaces. Inheritance remains appropriate for genuine is-a relationships with stable shared behaviour and shallow hierarchies, and the Liskov substitution principle is the test: if the subtype cannot replace the supertype, inheritance is the wrong tool.