Choosing Composition over Inheritance
In this pack:
sizing,
notation,
rule strictness.
Overview
A class that wants another class's work has two ways to get it. It can
extend the other class and inherit its messages, or it can hold an
instance and send messages to it. Extending is a statement about kinds:
a class that extends a collection is claiming to be a collection, and
every caller may treat it as one. Holding is a statement about use: the
holder offers only the messages it means to offer. This skill chooses
between the two, keeps a subclass from depending on how its parent is
written, and flattens hierarchies that cost more to read than they save.
When to use
- A subclass adds a rule or a convenience and wants the parent's code,
not its type.
- A change to a base class breaks subclasses that nobody edited.
- A design choice is between extending a class and holding an instance
of it.
- A class inherits a message it cannot honour, or overrides one to do
nothing.
- One behaviour takes three or more classes to follow.
- A mixin, module or trait is about to share state between classes that
are not related.
When not to use
- The class must extend a base type its framework requires, such as a
base controller or a test case class. Follow the framework and keep
domain rules out of that subclass.
- The subclass already keeps every promise of its parent, and the
question is how to state or check those promises. That is a question
of substitutability, not of reuse.
- The hierarchy exists to replace a repeated conditional on a type code.
The hierarchy is the answer there, so this skill would remove the
wrong thing.
Core rules
Default. Reuse behaviour by holding an object that has it and
forwarding to it, not by extending its class. A held object is asked
only through its public messages, and the class that holds it decides
which of those messages it offers. Extending a class says more than
reuse: it says the subclass can stand wherever the parent is expected.
The exception is a subclass that is a kind of its parent everywhere
the parent is used, and whose parent was built to be extended. Then
inheritance states that relationship directly, and a caller may use
the subclass in place of the parent.
Rule. Do not extend a class only to reuse its code. A subclass
offers every public message of its parent. If one of those messages
would let a caller break the subclass's rules, or the subclass has to
switch one off, hold the other class instead.
Rule. Never let a subclass depend on a send its parent keeps
internal. An override that works because the parent sends it from
another method breaks when the parent's author changes that internal
send. A class that holds the other object sees only its public
messages, and the internal sends cannot reach it. A parent built for
extension writes those sends into its contract, as honouring
substitutability's rule 5 asks, and then they are a promise a
subclass may rely on, not an internal send.
Judgement. Flatten a hierarchy when understanding one behaviour
means reading up and down several levels. Each level adds a place
where a message sent to the object itself can land. What tips the
balance is whether one class and its parent explain the behaviour.
Weigh what the reading costs against what the hierarchy explains; a
real kind-of relationship, as rule 1's exception allows, weighs on the
side of keeping it.
Default. Share behaviour across unrelated classes with an object
each one holds, not with a mixin, module or trait that reads or writes
the host's fields. A held object has its own fields and offers
messages. Code mixed into a host shares the host's fields and can
break rules the host keeps.
The exception is a mixin that uses only messages its host already
offers in public, such as an ordering built from a comparison the host
defines. It adds behaviour without touching the host's fields, so the
host cannot break it by changing a field.
Rule. Offer only the messages the reusing class means to offer.
Write one forwarding method for each message the reusing class
promises, and never forward the held object's whole interface by
habit. A narrow interface is the point of holding the object.
Pattern
Before, WaitingList extends a collection and adds one rule. After, it
holds a collection and offers only the messages its callers need.
Before:
class WaitingList extends List<PatientId>
+ join(patient: PatientId): void
raises AlreadyWaiting
if contains(patient) then
raise AlreadyWaiting
else
add(patient)
return
contains(patient) and add(patient) have no receiver, so each goes to
the WaitingList itself and lands on the collection it inherited. Every
message a List answers is now a public message of WaitingList, so a
caller can send add directly and put a patient on the list twice.
join adds no state, and the inherited add still lets any caller
append.
After:
class WaitingList
- patients: List<PatientId>
+ new()
patients := new List<PatientId>()
+ join(patient: PatientId): void
raises AlreadyWaiting
if patients.contains(patient) then
raise AlreadyWaiting
else
patients.add(patient)
return
+ waiting(): ReadOnlyList<PatientId>
return patients.readOnlyView()
new List<PatientId>() is taken to mean an empty list that the waiting
list owns. The constructor sets patients before join or waiting
reads it. join checks the held list, raises AlreadyWaiting without
appending when the patient is already there, and appends once otherwise.
waiting() returns a read-only view, so a caller reads the list but
cannot append to it. Only new, join and waiting are public: no
add, no contains, and no way to replace the list. The constructor is
plain because the list has one way to be made; a factory would add a step
without adding a rule.
Red flags
Places to look, not verdicts. A red flag becomes a finding only with
evidence: a measurement, a reproducible bug, or a failing test.
- A subclass that overrides a method to do nothing or to raise an error.
- A subclass that uses only a few of its parent's methods.
- An override that works only because the parent sends it from another
method.
- A hierarchy where reading one behaviour means opening three or more
classes.
- A mixin, module or trait that reads or writes its host's fields.
- A base class change that forces edits in subclasses nobody asked
about.
- A parent setter whose only callers are subclasses filling a field the
parent keeps private.
Common mistakes
- Replacing inheritance with a held object but forwarding every message,
which keeps the old interface and its problems.
- Treating any shared code as a reason to extend.
- Extending a class from a library or another team that was not built to
be extended.
- Switching off an inherited method by raising an error in the override.
- Using a mixin to share state between unrelated classes.
- Keeping a hierarchy because the classes look alike, when only their
code is shared.
- Expecting an override to keep running after the switch to holding,
when the held object's internal sends no longer reach the holder.
Related skills
Further reading
1---2name: oo-choosing-composition-over-inheritance3description: Use when a subclass only reuses code, when a base class change breaks its subclasses, or when choosing between extending a class and wrapping it.4license: MIT5metadata:6 source: https://skillmd.com/skills/yutna/oo-choosing-composition-over-inheritance7 version: 0.21.08 pack: object-oriented-design-skills9---1011# Choosing Composition over Inheritance1213**In this pack:**14[sizing](../oo-design/SKILL.md#how-much-design-a-task-warrants),15[notation](../oo-design/references/notation.md),16[rule strictness](../oo-design/SKILL.md#how-strictly-a-rule-is-meant).1718## Overview1920A class that wants another class's work has two ways to get it. It can21extend the other class and inherit its messages, or it can hold an22instance and send messages to it. Extending is a statement about kinds:23a class that extends a collection is claiming to be a collection, and24every caller may treat it as one. Holding is a statement about use: the25holder offers only the messages it means to offer. This skill chooses26between the two, keeps a subclass from depending on how its parent is27written, and flattens hierarchies that cost more to read than they save.2829## When to use3031- A subclass adds a rule or a convenience and wants the parent's code,32 not its type.33- A change to a base class breaks subclasses that nobody edited.34- A design choice is between extending a class and holding an instance35 of it.36- A class inherits a message it cannot honour, or overrides one to do37 nothing.38- One behaviour takes three or more classes to follow.39- A mixin, module or trait is about to share state between classes that40 are not related.4142## When not to use4344- The class must extend a base type its framework requires, such as a45 base controller or a test case class. Follow the framework and keep46 domain rules out of that subclass.47- The subclass already keeps every promise of its parent, and the48 question is how to state or check those promises. That is a question49 of substitutability, not of reuse.50- The hierarchy exists to replace a repeated conditional on a type code.51 The hierarchy is the answer there, so this skill would remove the52 wrong thing.5354## Core rules55561. Default. **Reuse behaviour by holding an object that has it and57 forwarding to it, not by extending its class.** A held object is asked58 only through its public messages, and the class that holds it decides59 which of those messages it offers. Extending a class says more than60 reuse: it says the subclass can stand wherever the parent is expected.6162 The exception is a subclass that is a kind of its parent everywhere63 the parent is used, and whose parent was built to be extended. Then64 inheritance states that relationship directly, and a caller may use65 the subclass in place of the parent.66672. Rule. **Do not extend a class only to reuse its code.** A subclass68 offers every public message of its parent. If one of those messages69 would let a caller break the subclass's rules, or the subclass has to70 switch one off, hold the other class instead.71723. Rule. **Never let a subclass depend on a send its parent keeps73 internal.** An override that works because the parent sends it from74 another method breaks when the parent's author changes that internal75 send. A class that holds the other object sees only its public76 messages, and the internal sends cannot reach it. A parent built for77 extension writes those sends into its contract, as honouring78 substitutability's rule 5 asks, and then they are a promise a79 subclass may rely on, not an internal send.80814. Judgement. **Flatten a hierarchy when understanding one behaviour82 means reading up and down several levels.** Each level adds a place83 where a message sent to the object itself can land. What tips the84 balance is whether one class and its parent explain the behaviour.85 Weigh what the reading costs against what the hierarchy explains; a86 real kind-of relationship, as rule 1's exception allows, weighs on the87 side of keeping it.88895. Default. **Share behaviour across unrelated classes with an object90 each one holds, not with a mixin, module or trait that reads or writes91 the host's fields.** A held object has its own fields and offers92 messages. Code mixed into a host shares the host's fields and can93 break rules the host keeps.9495 The exception is a mixin that uses only messages its host already96 offers in public, such as an ordering built from a comparison the host97 defines. It adds behaviour without touching the host's fields, so the98 host cannot break it by changing a field.991006. Rule. **Offer only the messages the reusing class means to offer.**101 Write one forwarding method for each message the reusing class102 promises, and never forward the held object's whole interface by103 habit. A narrow interface is the point of holding the object.104105## Pattern106107Before, `WaitingList` extends a collection and adds one rule. After, it108holds a collection and offers only the messages its callers need.109110Before:111112```text113class WaitingList extends List<PatientId>114 + join(patient: PatientId): void115 raises AlreadyWaiting116 if contains(patient) then117 raise AlreadyWaiting118 else119 add(patient)120 return121```122123`contains(patient)` and `add(patient)` have no receiver, so each goes to124the `WaitingList` itself and lands on the collection it inherited. Every125message a `List` answers is now a public message of `WaitingList`, so a126caller can send `add` directly and put a patient on the list twice.127`join` adds no state, and the inherited `add` still lets any caller128append.129130After:131132```text133class WaitingList134 - patients: List<PatientId>135 + new()136 patients := new List<PatientId>()137 + join(patient: PatientId): void138 raises AlreadyWaiting139 if patients.contains(patient) then140 raise AlreadyWaiting141 else142 patients.add(patient)143 return144 + waiting(): ReadOnlyList<PatientId>145 return patients.readOnlyView()146```147148`new List<PatientId>()` is taken to mean an empty list that the waiting149list owns. The constructor sets `patients` before `join` or `waiting`150reads it. `join` checks the held list, raises `AlreadyWaiting` without151appending when the patient is already there, and appends once otherwise.152`waiting()` returns a read-only view, so a caller reads the list but153cannot append to it. Only `new`, `join` and `waiting` are public: no154`add`, no `contains`, and no way to replace the list. The constructor is155plain because the list has one way to be made; a factory would add a step156without adding a rule.157158## Red flags159160Places to look, not verdicts. A red flag becomes a finding only with161evidence: a measurement, a reproducible bug, or a failing test.162163- A subclass that overrides a method to do nothing or to raise an error.164- A subclass that uses only a few of its parent's methods.165- An override that works only because the parent sends it from another166 method.167- A hierarchy where reading one behaviour means opening three or more168 classes.169- A mixin, module or trait that reads or writes its host's fields.170- A base class change that forces edits in subclasses nobody asked171 about.172- A parent setter whose only callers are subclasses filling a field the173 parent keeps private.174175## Common mistakes176177- Replacing inheritance with a held object but forwarding every message,178 which keeps the old interface and its problems.179- Treating any shared code as a reason to extend.180- Extending a class from a library or another team that was not built to181 be extended.182- Switching off an inherited method by raising an error in the override.183- Using a mixin to share state between unrelated classes.184- Keeping a hierarchy because the classes look alike, when only their185 code is shared.186- Expecting an override to keep running after the switch to holding,187 when the held object's internal sends no longer reach the holder.188189## Related skills190191- [oo-design](../oo-design/SKILL.md) sizes a task and defines the rule192 labels.193- [oo-encapsulating-state-and-behaviour](../oo-encapsulating-state-and-behaviour/SKILL.md)194 keeps the held object's state behind its own messages and returns a195 read-only view from a query.196- [oo-encapsulating-what-varies](../oo-encapsulating-what-varies/SKILL.md)197 isolates the part that changes behind an interface, which is how a held198 collaborator is chosen.199- [oo-honouring-substitutability](../oo-honouring-substitutability/SKILL.md)200 states the contract a subclass must keep, which is what rule 3 relies201 on when the parent is written for extension.202203## Further reading204205- [Fragile hierarchies](references/fragile-hierarchies.md)