Inheritance vs composition
medium 40 minTwo ways to reuse code.
Video lesson · Chapter 1 of 6
Make a prediction
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
1967
Simula 67 brings classes and subclasses, presented by Ole-Johan Dahl and Kristen Nygaard.
1986
Alan Snyder publishes Encapsulation and Inheritance in Object-Oriented Programming Languages. It describes how subclasses can break the encapsulation of their parent.
1987
Barbara Liskov's keynote Data Abstraction and Hierarchy asks what a subtype must guarantee. This became the substitution principle.
1994
Gamma, Helm, Johnson and Vlissides publish Design Patterns, with the advice to favor object composition.
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.
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 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?
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.Bird with a promise too much
1/4The base class
fly is promised for every bird.
usesextends (is a)
Behaviours as parts
1/5Two abilities
Flying and swimming become small interfaces with their own classes.
has (lives on)implements
Compare
Side by side
| Aspect | Inheritance | Composition |
|---|---|---|
| Relation | is a | has a |
| Coupling | tight: to the parent's inside and its calls to itself | loose: to public methods |
| Chosen | when the class is written | when the object is made, and later |
| Reuse | implicit: all of it comes along | explicit: you forward what you want |
| Encapsulation | weakened: the child sees protected parts | kept |
| Combining features | one subclass per combination | one object per feature |
| Testing | the parent always runs | pass a fake part |
| Typing effort | little | forwarding methods |
| Used as the parent type | yes | only with a shared interface |
One call, then a swap
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.
| Formats | Targets | Subclasses | Parts |
|---|---|---|---|
| 2 | 2 | 4 | 4 |
| 3 | 3 | 9 | 6 |
| 4 | 5 | 20 | 9 |
| 5 and 3 ways to sign | 5 | 75 | 13 |
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
addAllorextendmay or may not calladd. 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
Listis 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). MoreDecorator
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
- Gamma, Helm, Johnson, Vlissides: Design Patterns (1994), introduction. Book, not online
- Alan Snyder, Encapsulation and Inheritance in Object-Oriented Programming Languages (1986)
- Barbara Liskov, Data Abstraction and Hierarchy (1987)
- Java 21 API: Stack
- Java 21 API: Properties
- Guava: ForwardingSet
- Kotlin: delegation
- Effective Go: embedding
- React (legacy docs): composition vs inheritance
- Unity manual: GameObject
- Python: collections.UserDict
- JEP 409: Sealed Classes