Composition over inheritance

  • Lesson 3 of 32
  • 10 min
  • Beginner
  • 11 steps

Inheritance is often the first thing you learn about object-oriented programming, so it ends up used for everything. Here you will see where it breaks and what to do instead: build objects out of parts.

Classes with inheritance
16
Pieces with composition
6
DuckDuck ·rubberDuckFlyingDuckFlyingDuckSwimmingDuckSwimmingDuckFlyingSwimmingDuckFlyingSwimmingDuckswimswimflyflyquackquackdivediveSkillinterfaceSkillReaderabstractReaderBufferedReaderBufferedReaderInputStreamReaderInputStreamReaderyour programWelcomeDialogWelcomeDialogDialogDialogFancyBorderFancyBorderInheritanceclass Duck { name = "duck"; }class FlyingDuck extends Duck {fly() { return "flies"; }}class SwimmingDuck extends Duck {swim() { return "swims"; }}is a Duck · fliesis a Duck · swims2 × 2 × 2 = 8 classesDuckFlyingDuckSwimmingDuck+QuackingDuckFlyingSwimmingDuck+FlyingQuackingDuck+SwimmingQuackingDuck+FlyingSwimmingQuackingDuckswim() copied+4 classes with quackA change in the base classclass Duck {+fly() { return "flies"; }}class SwimmingDuck extends Duck {}new SwimmingDuck().fly();// "flies": nobody asked+ fly() in the basenow it flies!Has a, not is ainterface Skill {use(): string;}class Duck {constructor(private skills: Skill[]) {}}interface: the contractDuck has SkillsComposition+const fly = { use: () => "flies" };+const swim = { use: () => "swims" };+const quack = { use: () => "quacks" };class Duck {constructor(private skills: Skill[]) {}act() { return this.skills.map((s) => s.use()); }}delegates to its parts3 implementationsReact: composing componentsfunction WelcomeDialog() {return (<Dialog title="Welcome"message="Thanks for visiting" />);}props: title, messagechildrenuses Dialog, does not extend itCombine when creatingconst mallard =new Duck([fly, swim, quack]);+const rubber =+new Duck([swim, quack]);rubber.act(); // ["swims", "quacks"]rubber duck: swims and quacksnot usedOne more skill+const dive: Skill = {+use: () => "dives" };+new Duck([swim, dive]);new partDuck does not changeJava: java.ioBufferedReader in =new BufferedReader(new InputStreamReader(System.in));String line = in.readLine();is a Reader and has a Readerstable abstract classInheritance or compositionInheritanceless code up frontfragile if the base changesCompositionswappable partsmore objects and wiringInherit when…a real, stable «is a»or the framework asks for itmore objects to wireone more interfacehas partsdepends on the interface
  • request
  • response

Step 1 of 11

Problem

Inheriting to reuse code

You have a Duck class and you want ducks that fly and ducks that swim. The first idea: two subclasses, FlyingDuck and SwimmingDuck, that extend Duck and add one method each.

It works and it is little code. The arrows with a hollow triangle mean «extends»: each subclass is a Duck. Then the first new request arrives: a duck that flies and swims.

Step 2 of 11

Problem

One class per combination

In TypeScript a class can extend only one class. FlyingSwimmingDuck inherits from FlyingDuck and has to copy the swimming code from SwimmingDuck.

Then you are asked for ducks that quack. With 3 skills that combine freely there are 2 × 2 × 2 = 8 combinations, counting the Duck that does nothing: 8 classes. A fourth skill would make it 16.

What changed

  • FlyingSwimmingDuck, with swim() copied
  • 4 more classes for quacking
  • Classes: from 3 to 8

Step 3 of 11

Problem

The fragile base class

To avoid repeating code, someone moves fly() into Duck. Now every subclass inherits it, including SwimmingDuck, which stands for a rubber duck: new SwimmingDuck().fly() returns "flies".

This is the fragile base class problem: a reasonable change in the parent changes the behaviour of children nobody touched, and the compiler does not warn you.

What changed

  • fly() moved into Duck
  • SwimmingDuck inherits a fly() it should not have

Step 4 of 11

Concept

Has a, not is a

The alternative is composition: instead of Duck being several things, Duck has parts. Each skill is a separate object that meets a Skill interface with a single method, use().

Duck only knows the interface (the block with a dashed outline), not each concrete skill. The design patterns book by Gamma, Helm, Johnson and Vlissides (1994) recommends exactly this: favour object composition over class inheritance.

What changed

  • Subclass hierarchy
  • Skill interface
  • Duck receives its Skills when created

Step 5 of 11

Technique

Duck delegates to its parts

fly, swim and quack are small objects that implement Skill (dashed arrow with a triangle). When you ask Duck to act, it walks through its parts and delegates the work to each one: those are the requests and responses on the lines.

You write 5 pieces: Duck, Skill and 3 skills. With inheritance it was 8 classes, and every new skill doubles them.

What changed

  • fly, swim and quack implement Skill
  • Pieces: 5 instead of 8 classes

Step 6 of 11

Concept

Real case: React components

React applies the same idea to user interfaces. In its documentation (the older version, legacy.reactjs.org) the example is a WelcomeDialog: instead of inheriting from Dialog, it uses it and configures it with props (title, message). Dialog, in turn, wraps its content in a FancyBorder through children.

The same page says that at Facebook they used React in thousands of components and had not found any case where they would recommend creating component inheritance hierarchies.

What changed

  • WelcomeDialog uses Dialog with props
  • Dialog wraps its children in FancyBorder

Step 7 of 11

Solution

Each duck with the parts it needs

Back to the ducks. The rubber duck no longer needs its own class: it is a Duck created with [swim, quack]. The real duck is created with all three parts. The same class covers every combination.

And since the parts are objects, you can also swap them while the program runs: an injured duck can lose fly, something a subclass cannot do because its type was fixed when it was written.

What changed

  • rubber = new Duck([swim, quack])
  • fly unused by this duck

Step 8 of 11

Solution

A new skill without touching Duck

Now you are asked for ducks that dive. You write one new part, dive, that implements Skill. Duck does not change a single line, and no existing duck changes its behaviour.

With inheritance, a fourth skill takes the count to 2 × 2 × 2 × 2 = 16 classes. With composition you go from 5 pieces to 6: it grows by adding, not multiplying.

What changed

  • dive part
  • Inheritance: 16 classes · composition: 6 pieces

Step 9 of 11

Technique

Real case: inheritance and composition together

In Java, BufferedReader extends the abstract class Reader and also receives another Reader in its constructor, which it wraps. The Java documentation advises wrapping a BufferedReader around any Reader whose reads may be costly, such as FileReader or InputStreamReader.

So there is no BufferedFileReader, BufferedStringReader…: one class adds the buffer to any source. Inheritance here is shallow and stable (the Reader contract); the extra behaviour comes through composition.

What changed

  • BufferedReader extends Reader
  • BufferedReader wraps an InputStreamReader

Step 10 of 11

Trade-off

When inheritance does fit

Composition has a cost: more objects, one more interface and someone who has to wire the parts when creating each duck. For a case that will never vary, it can be too much ceremony.

Inheritance is fine for a real, stable «is a» with a shallow hierarchy, or when a framework asks you to extend a base class that it calls itself (you will see it in Template Method). Do not use it just to reuse a few methods.

Step 11 of 11

Summary

Summary

Inheriting to combine behaviours multiplies classes and copies code.

A base class is fragile: its changes reach every child.

With composition, an object has parts behind an interface and delegates the work to them.

Parts are combined when the object is created and added without touching the class.

Inherit for a real, stable «is a»; compose to combine.

You will learn

  • Spot the subclass explosion
  • Explain the fragile base class problem
  • Compose behaviour with interfaces («has a»)
  • Combine and add parts without touching the class
  • Choose inheritance when it really fits