AlgoViz

Inheritance vs composition

medium 40 min

Two ways to reuse code.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:52

Inheritance vs composition

1:01Reel

Theory

Read or listen first. About 2 min.

What it is

Inheritance: a new class (subclass) is made from an existing one (superclass). It gets all its fields and methods, may add some and may override some. It also becomes a subtype: it can be used wherever the parent is expected. This is the is-a relation.

Composition: a class holds other objects and passes work on to them. This is the has-a relation. Passing a call on is called delegation.

Inheritance therefore does two jobs at once: it reuses code and it promises a type. Most trouble comes from wanting only the first and getting the second as well.

Why it exists

The choice decides how hard the code is to change. A subclass depends on how its parent works inside. An object that holds a part depends only on the part's public methods.

A parent is chosen when the code is written. A part can be chosen when the program runs, and it can be changed later.

One parent gives one axis. Real things vary along several: how it flies, how it swims, how it is drawn. Parts can be combined freely.

The rule of thumb from the book Design Patterns: “Favor object composition over class inheritance.” It says favor. It does not say always.

A short history

  1. 1967

    Simula 67 brings classes and subclasses, presented by Ole-Johan Dahl and Kristen Nygaard.

  2. 1986

    Alan Snyder publishes Encapsulation and Inheritance in Object-Oriented Programming Languages. It describes how subclasses can break the encapsulation of their parent.

  3. 1987

    Barbara Liskov's keynote Data Abstraction and Hierarchy asks what a subtype must guarantee. This became the substitution principle.

  4. 1994

    Gamma, Helm, Johnson and Vlissides publish Design Patterns, with the advice to favor object composition.

  5. 2021

    Java 17 finishes sealed classes (JEP 409): a class can list who may extend it.

Words to know

Superclass, subclass
Parent and child. Also called base and derived class.
Override
A subclass gives its own body to a method of the parent.
Delegation
An object passes a call on to a part that it holds.
Forwarding wrapper
An object with the same interface as its part. It passes calls on and may add something.
Fragile base class
A safe looking change in a parent breaks a subclass that nobody looked at.
Self-use
A class calls its own overridable methods. Then overriding one changes the other.
Substitutability
Each subclass object works where a parent object is expected, without surprises.
Class explosion
One subclass for each combination of features.

The solution, twice

Reach the regular design first. Then go where a FAANG interviewer digs.

How it works

Step through the idea, or press Play.

Step 1 of 5

Ask: is a?. In behaviour, not only in words

Understand it

Start here

One big stencil, or small stamps

The class paints boats for a summer fair. Watch what happens when one boat should be different.

The boat stencil

The stencil is not bad. It is right when all boats really are the same boat.

Two toys show the same. Nesting dolls are inheritance: each smaller doll has the shape of the one around it, and a square doll does not fit. Building bricks are composition: snap on wheels and it is a car, snap on wings and it is a plane.

The classic trap

The penguin problem

Birds fly, so Bird gets fly(). A penguin is a bird, so Penguin extends Bird. Now what does its fly() do?

Python
class Bird:    def fly(self):        return "flying"class Eagle(Bird):    passclass Penguin(Bird):    def fly(self):        raise NotImplementedError("penguins cannot fly")def air_show(birds: list[Bird]):    return [b.fly() for b in birds]        # expects that each bird canprint(air_show([Eagle()]))try:    air_show([Eagle(), Penguin()])except NotImplementedError as e:    print("the show stopped:", e)
air_show did nothing wrong. It trusted the type.
Edit and run it in your browser

Bird with a promise too much

Bird+ fly()

1/4The base class

fly is promised for every bird.

usesextends (is a)

This is a broken substitution. The full rules are on the page about Liskov substitution.

Behaviours as parts

«interface»FlyBehavior+ fly(name)«interface»SwimBehavior+ swim(name)Wings+ fly(name)Flippers+ swim(name)

1/5Two abilities

Flying and swimming become small interfaces with their own classes.

has (lives on)implements

This is the Strategy pattern, used once for each ability.

Compare

Side by side

AspectInheritanceComposition
Relationis ahas a
Couplingtight: to the parent's inside and its calls to itselfloose: to public methods
Chosenwhen the class is writtenwhen the object is made, and later
Reuseimplicit: all of it comes alongexplicit: you forward what you want
Encapsulationweakened: the child sees protected partskept
Combining featuresone subclass per combinationone object per feature
Testingthe parent always runspass a fake part
Typing effortlittleforwarding methods
Used as the parent typeyesonly with a shared interface

One call, then a swap

One extra hop buys the freedom to change the part.

The hidden trap

Fragile base class

A subclass overrides add and add_all to count items. It counts each item twice, because the parent's add_all calls add on itself, and that call lands in the subclass. The code of the subclass looks right. It depends on a detail that is not in any contract. The FAANG pages walk through this bug.

Counted twice

Combinations

Class explosion

A report can be PDF, HTML or text. It can go by mail, to a disk or to a printer. With inheritance that is 3 times 3, nine classes, and one more format adds three. With two parts it is 3 plus 3, six classes, and one more format adds one.

FormatsTargetsSubclassesParts
2244
3396
45209
5 and 3 ways to sign57513
Multiply or add. The two shapes have the same size at 2 by 2. That is why the problem is not visible at the start.

Decide

When to use which

Inheritance when

  • A true is-a, also in behaviour
  • The child can stand in for the parent everywhere
  • The hierarchy is small and stable
  • You override specific, documented steps
  • A framework asks for it, such as a test case class

Not inheritance, but composition when

  • It is has-a, or is-like-a
  • The behaviour may change at run time
  • Several features combine
  • You want to avoid the fragile base class
  • Tests should replace the collaborator

Which one?

An AuditedList must behave like a list and write a line for each added item. How do you build it?

BreaksExtend the library list and override add
How
Short, and it is a list at once.
Limit
Other methods such as addAll or extend may or may not call add. The next version may differ.
Choose when
Never for a class that was not made for it.
WorksExtend and override every adding method
How
Read the documentation and cover all of them.
Limit
A new method in the next version goes around you.
Choose when
Your own base class with documented hooks.
StrongWrap a list and implement the small interface you need
How
add(item) writes the line and forwards.
Limit
Forwarding methods to write. Where a full List is needed, use a forwarding base class.
Choose when
The default.

Patterns

Composition has many names

  • Strategy

    Hold an algorithm and swap it: context.setStrategy(s). More

  • Decorator

    Wrap an object with the same interface and add something. More

  • Adapter

    Hold an object with the wrong interface and translate. More

  • Bridge

    Two axes, two hierarchies, one holds the other. More

  • Dependency injection

    Receive the part in the constructor. More

  • Mixins and traits

    Language tools between the two. More

Inheritance has a pattern of its own: Template method, a fixed frame with a few planned gaps. It works because the gaps are planned.

Several parents

What about a duck with two parents?

Single inheritance cannot express a duck that is a flying bird and a swimming bird. Multiple inheritance can, and brings the question of which version wins when both parents have the same method or the same grandparent. That story is on The diamond problem. Composition does not have the question: the duck holds two parts with two names.

Neighbours

How it fits

IS-A and HAS-A shows how to read the relation. Object composition shows how to build with parts. Liskov substitution defines stand in. Preventing subclassing shows how to close a class.

Summary

The whole topic in one minute.

Inheritance reuses code and promises a type in one step. It fits a true is-a that can stand in for its parent, in a small hierarchy that was made for it. Outside of that it brings unwanted methods, fragile parents and too many classes.

Composition holds parts behind small interfaces and passes work on. It costs some forwarding code and buys loose coupling, free combination and replacement at run time. Start with composition, and inherit when you can say why.

  • Inheritance gives code and type together. Often you want only one.
  • Penguin: is-a in words is not enough, the behaviour must fit.
  • A subclass depends on how its parent calls itself.
  • Two axes: inheritance multiplies, composition adds.
  • Parts can be swapped, faked and combined.
  • Inherit when it can stand in, the parent is made for it, and the tree is shallow.

Sources