Choosing a Pattern
In this pack:
sizing,
notation,
rule strictness.
Overview
A pattern is a named arrangement that answers a problem which returns.
It earns its place only when the problem is in the code now: a second
case has arrived, a change keeps coming back, or a duplication has
already drifted apart, or when the business has named the variation with
a reason. This skill starts from the symptom, checks the pattern's force
with evidence, weighs its cost against what it removes, and takes the
pattern out again when the force goes.
When to use
- A symptom in the code needs a name, such as a copied step or a choice
that keeps changing, and you are choosing a pattern for it.
- A pattern was added before the code showed its force, and the team is
deciding what to keep.
- A module is hard to change and a pattern is proposed as the answer.
- A pattern is still in the code after its last variant has gone.
- A design review asks whether a pattern pays its way.
When not to use
- The code has one case and no duplication, and nobody has named a
change that recurs: no pattern is needed. Build the one case and look
again when a second arrives.
- The question is how a known force is treated, such as a status that
changes an object's behaviour or a complex construction: the skill
that owns the force answers it, such as
modeling lifecycles,
replacing conditionals with
polymorphism
or constructing valid
objects.
- The question is whether the language already provides the pattern as
a feature. That is a question about a feature the language offers,
which patterns the language
provides decides.
- The question is a pattern's syntax in one programming language. That
is outside this skill.
Core rules
Rule. Start from the symptom in the code, never from a pattern:
name what is duplicated, what keeps changing, or what is hard to
test, and look up the patterns that answer that symptom. A pattern
chosen first goes looking for a problem. A copied cancellation line
in two channels is a symptom; start there, and
the catalogue names the
decoration that removes the copy.
Rule. Add a pattern only when its force is present in the code
now, with evidence, such as a second case that has arrived, a change
that keeps coming back, or a duplication that has already drifted
apart, or when the business has named the variation with a
reason. That is what encapsulating what
varies rules 1 and 4 ask
for before any seam. A pattern without that evidence is a guess
about a change nobody has seen.
Rule. Weigh a pattern's cost before adding it: the classes and the
indirection it adds, and the name every reader must then know. Add
it when that cost is smaller than the duplication or the repeated
change it removes. A decorator costs one wrapper class and one line
at the composition root; it pays when three channels would otherwise
copy the same step.
Default. Reach first for the plainest construct that resolves the
force: a value, a function or a feature the language offers before a
hierarchy of classes. A value or a function is cheaper to read than
an interface and a class per case.
The exception is a force the module already answers with a pattern:
follow the module's choice, so one force has one answer in it.
Default. Build a pattern in the clinic's words: its classes keep
domain names, such as CancelLineChannel rather than
ChannelDecorator, as naming classes and
methods rule 1 asks, and
the pattern's name goes where it helps a reader, such as the design
notes. The name by which callers meet the class is the clinic's
concept, not the mechanism.
The exception is a class whose job is the mechanism itself, such as
an adapter for an outside system or a repository: its pattern word
is its meaning, as the exception to naming classes and methods,
rule 3, and designing
repositories rule 1 allow.
Rule. Remove a pattern when its force has gone: a strategy with
one implementation left, or a factory that builds one type, becomes
a direct construction again; an observer with one listener in the
same module becomes a direct message when its reaction must happen
at once, while one whose reaction runs after the change commits
stays an event, as publishing domain
events rule 6 decides.
Keeping the machinery after the variation ends leaves a reader to
learn a name that buys nothing.
Pattern
Before, every reminder channel adds the clinic's how-to-cancel line
itself. The same step is copied into EmailChannel and TextChannel,
and a third channel would copy it again.
Before:
value Reminder
- patient: PatientId
- text: String
- mobile: String?
+ new(patient: PatientId, text: String, mobile: String?)
+ patient(): PatientId
return patient
+ text(): String
return text
+ mobile(): String?
return mobile
+ withFooter(line: String): Reminder
return new Reminder(patient, text.appendLine(line), mobile)
interface ReminderChannel
+ send(reminder: Reminder): void
-- delivers the reminder or hands it on, and raises nothing
class EmailChannel implements ReminderChannel
- mailer: Mailer
- cancelLine: String
+ new(mailer: Mailer, cancelLine: String)
+ send(reminder: Reminder): void
mailer.send(reminder.patient(), reminder.withFooter(cancelLine).text())
return
class TextChannel implements ReminderChannel
- gateway: TextGateway
- cancelLine: String
+ new(gateway: TextGateway, cancelLine: String)
+ send(reminder: Reminder): void
gateway.sendText(reminder.patient(), reminder.withFooter(cancelLine).text())
return
EmailChannel here is the substitutability skill's class with a
cancelLine field and a constructor parameter added; its send
signature and mailer field are that skill's, and the line it adds is
the copy this Before shows. Reminder and ReminderChannel are that
skill's, apart from one message this skill adds. withFooter(line) is
a message this skill adds to Reminder, taken to answer a copy of the
reminder with that line added at its end; text.appendLine(line) is
taken to answer the reminder's text with the line added at its end.
TextChannel and TextGateway are new here. Mailer.send and
TextGateway.sendText are taken to send one email and one text. The
fence stores nothing.
After, one class adds the line around any channel. EmailChannel is the
substitutability skill's class exactly; TextChannel holds only its
gateway, and both send the reminder they are given. CancelLineChannel
adds the line and hands the reminder on, so a third channel needs no copy
of the step.
After:
value Reminder
- patient: PatientId
- text: String
- mobile: String?
+ new(patient: PatientId, text: String, mobile: String?)
+ patient(): PatientId
return patient
+ text(): String
return text
+ mobile(): String?
return mobile
+ withFooter(line: String): Reminder
return new Reminder(patient, text.appendLine(line), mobile)
interface ReminderChannel
+ send(reminder: Reminder): void
-- delivers the reminder or hands it on, and raises nothing
class EmailChannel implements ReminderChannel
- mailer: Mailer
+ new(mailer: Mailer)
+ send(reminder: Reminder): void
mailer.send(reminder.patient(), reminder.text())
return
class TextChannel implements ReminderChannel
- gateway: TextGateway
+ new(gateway: TextGateway)
+ send(reminder: Reminder): void
gateway.sendText(reminder.patient(), reminder.text())
return
class CancelLineChannel implements ReminderChannel
- inner: ReminderChannel
- cancelLine: String
+ new(inner: ReminderChannel, cancelLine: String)
+ send(reminder: Reminder): void
inner.send(reminder.withFooter(cancelLine))
return
ReminderChannel and Reminder are the substitutability skill's:
send delivers the reminder or hands it on and raises nothing, and
Reminder answers patient() and text(). CancelLineChannel keeps
that promise, because it always hands the reminder on. withFooter is
the message this skill adds, as the Before explains. The pattern is a
decorator, named here; CancelLineChannel keeps the clinic's word for
it. The composition root, outside this fence, wraps each channel once in
a CancelLineChannel. Every reminder is sent once, with the line added
once: an unwrapped channel sends the reminder it is given once, and a
wrapped channel adds the line to a copy once and hands that copy to its
inner channel once. Both fences store nothing.
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 pattern whose force nobody can point to in the code.
- An interface with one implementation, other than a port to an outside
system, or a factory with one product.
- An observer with one listener in the same module whose reaction must
happen at once.
- Class names made only of pattern words, such as
AppointmentFactoryImpl or ChannelDecorator, on a class whose job
is a clinic concept.
- The same check or step copied into every implementation of one
interface.
- Two patterns answering one force in one module.
Common mistakes
- Choosing a pattern because a catalogue lists it, before the code shows
its force.
- Keeping a pattern after its last variant has gone.
- Adding a class hierarchy where a value or a function would do.
- Naming classes after the pattern instead of the clinic's concept.
- Combining several patterns at once to make a module ready for every
change.
Related skills
Further reading
- Patterns by problem
- Patterns beyond objects
1---2name: oo-choosing-a-pattern3description: Use when picking a design pattern for a problem, when a pattern was added before its problem, or when deciding if a pattern still pays its way.4license: MIT5metadata:6 source: https://skillmd.com/skills/yutna/oo-choosing-a-pattern7 version: 0.21.08 pack: object-oriented-design-skills9---1011# Choosing a Pattern1213**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 pattern is a named arrangement that answers a problem which returns.21It earns its place only when the problem is in the code now: a second22case has arrived, a change keeps coming back, or a duplication has23already drifted apart, or when the business has named the variation with24a reason. This skill starts from the symptom, checks the pattern's force25with evidence, weighs its cost against what it removes, and takes the26pattern out again when the force goes.2728## When to use2930- A symptom in the code needs a name, such as a copied step or a choice31 that keeps changing, and you are choosing a pattern for it.32- A pattern was added before the code showed its force, and the team is33 deciding what to keep.34- A module is hard to change and a pattern is proposed as the answer.35- A pattern is still in the code after its last variant has gone.36- A design review asks whether a pattern pays its way.3738## When not to use3940- The code has one case and no duplication, and nobody has named a41 change that recurs: no pattern is needed. Build the one case and look42 again when a second arrives.43- The question is how a known force is treated, such as a status that44 changes an object's behaviour or a complex construction: the skill45 that owns the force answers it, such as46 [modeling lifecycles](../oo-modeling-lifecycles/SKILL.md),47 [replacing conditionals with48 polymorphism](../oo-replacing-conditionals-with-polymorphism/SKILL.md)49 or [constructing valid50 objects](../oo-constructing-valid-objects/SKILL.md).51- The question is whether the language already provides the pattern as52 a feature. That is a question about a feature the language offers,53 which [patterns the language54 provides](../oo-patterns-the-language-provides/SKILL.md) decides.55- The question is a pattern's syntax in one programming language. That56 is outside this skill.5758## Core rules59601. Rule. **Start from the symptom in the code, never from a pattern:61 name what is duplicated, what keeps changing, or what is hard to62 test, and look up the patterns that answer that symptom.** A pattern63 chosen first goes looking for a problem. A copied cancellation line64 in two channels is a symptom; start there, and65 [the catalogue](references/patterns-by-problem.md) names the66 decoration that removes the copy.67682. Rule. **Add a pattern only when its force is present in the code69 now, with evidence, such as a second case that has arrived, a change70 that keeps coming back, or a duplication that has already drifted71 apart, or when the business has named the variation with a72 reason.** That is what [encapsulating what73 varies](../oo-encapsulating-what-varies/SKILL.md) rules 1 and 4 ask74 for before any seam. A pattern without that evidence is a guess75 about a change nobody has seen.76773. Rule. **Weigh a pattern's cost before adding it: the classes and the78 indirection it adds, and the name every reader must then know.** Add79 it when that cost is smaller than the duplication or the repeated80 change it removes. A decorator costs one wrapper class and one line81 at the composition root; it pays when three channels would otherwise82 copy the same step.83844. Default. **Reach first for the plainest construct that resolves the85 force: a value, a function or a feature the language offers before a86 hierarchy of classes.** A value or a function is cheaper to read than87 an interface and a class per case.8889 The exception is a force the module already answers with a pattern:90 follow the module's choice, so one force has one answer in it.91925. Default. **Build a pattern in the clinic's words: its classes keep93 domain names, such as `CancelLineChannel` rather than94 `ChannelDecorator`, as [naming classes and95 methods](../oo-naming-classes-and-methods/SKILL.md) rule 1 asks, and96 the pattern's name goes where it helps a reader, such as the design97 notes.** The name by which callers meet the class is the clinic's98 concept, not the mechanism.99100 The exception is a class whose job is the mechanism itself, such as101 an adapter for an outside system or a repository: its pattern word102 is its meaning, as the exception to naming classes and methods,103 rule 3, and [designing104 repositories](../oo-designing-repositories/SKILL.md) rule 1 allow.1051066. Rule. **Remove a pattern when its force has gone: a strategy with107 one implementation left, or a factory that builds one type, becomes108 a direct construction again; an observer with one listener in the109 same module becomes a direct message when its reaction must happen110 at once, while one whose reaction runs after the change commits111 stays an event, as [publishing domain112 events](../oo-publishing-domain-events/SKILL.md) rule 6 decides.**113 Keeping the machinery after the variation ends leaves a reader to114 learn a name that buys nothing.115116## Pattern117118Before, every reminder channel adds the clinic's how-to-cancel line119itself. The same step is copied into `EmailChannel` and `TextChannel`,120and a third channel would copy it again.121122Before:123124```text125value Reminder126 - patient: PatientId127 - text: String128 - mobile: String?129 + new(patient: PatientId, text: String, mobile: String?)130 + patient(): PatientId131 return patient132 + text(): String133 return text134 + mobile(): String?135 return mobile136 + withFooter(line: String): Reminder137 return new Reminder(patient, text.appendLine(line), mobile)138139interface ReminderChannel140 + send(reminder: Reminder): void141 -- delivers the reminder or hands it on, and raises nothing142143class EmailChannel implements ReminderChannel144 - mailer: Mailer145 - cancelLine: String146 + new(mailer: Mailer, cancelLine: String)147 + send(reminder: Reminder): void148 mailer.send(reminder.patient(), reminder.withFooter(cancelLine).text())149 return150151class TextChannel implements ReminderChannel152 - gateway: TextGateway153 - cancelLine: String154 + new(gateway: TextGateway, cancelLine: String)155 + send(reminder: Reminder): void156 gateway.sendText(reminder.patient(), reminder.withFooter(cancelLine).text())157 return158```159160`EmailChannel` here is the substitutability skill's class with a161`cancelLine` field and a constructor parameter added; its `send`162signature and `mailer` field are that skill's, and the line it adds is163the copy this Before shows. `Reminder` and `ReminderChannel` are that164skill's, apart from one message this skill adds. `withFooter(line)` is165a message this skill adds to `Reminder`, taken to answer a copy of the166reminder with that line added at its end; `text.appendLine(line)` is167taken to answer the reminder's text with the line added at its end.168`TextChannel` and `TextGateway` are new here. `Mailer.send` and169`TextGateway.sendText` are taken to send one email and one text. The170fence stores nothing.171172After, one class adds the line around any channel. `EmailChannel` is the173substitutability skill's class exactly; `TextChannel` holds only its174gateway, and both send the reminder they are given. `CancelLineChannel`175adds the line and hands the reminder on, so a third channel needs no copy176of the step.177178After:179180```text181value Reminder182 - patient: PatientId183 - text: String184 - mobile: String?185 + new(patient: PatientId, text: String, mobile: String?)186 + patient(): PatientId187 return patient188 + text(): String189 return text190 + mobile(): String?191 return mobile192 + withFooter(line: String): Reminder193 return new Reminder(patient, text.appendLine(line), mobile)194195interface ReminderChannel196 + send(reminder: Reminder): void197 -- delivers the reminder or hands it on, and raises nothing198199class EmailChannel implements ReminderChannel200 - mailer: Mailer201 + new(mailer: Mailer)202 + send(reminder: Reminder): void203 mailer.send(reminder.patient(), reminder.text())204 return205206class TextChannel implements ReminderChannel207 - gateway: TextGateway208 + new(gateway: TextGateway)209 + send(reminder: Reminder): void210 gateway.sendText(reminder.patient(), reminder.text())211 return212213class CancelLineChannel implements ReminderChannel214 - inner: ReminderChannel215 - cancelLine: String216 + new(inner: ReminderChannel, cancelLine: String)217 + send(reminder: Reminder): void218 inner.send(reminder.withFooter(cancelLine))219 return220```221222`ReminderChannel` and `Reminder` are the substitutability skill's:223`send` delivers the reminder or hands it on and raises nothing, and224`Reminder` answers `patient()` and `text()`. `CancelLineChannel` keeps225that promise, because it always hands the reminder on. `withFooter` is226the message this skill adds, as the Before explains. The pattern is a227decorator, named here; `CancelLineChannel` keeps the clinic's word for228it. The composition root, outside this fence, wraps each channel once in229a `CancelLineChannel`. Every reminder is sent once, with the line added230once: an unwrapped channel sends the reminder it is given once, and a231wrapped channel adds the line to a copy once and hands that copy to its232inner channel once. Both fences store nothing.233234## Red flags235236Places to look, not verdicts. A red flag becomes a finding only with237evidence: a measurement, a reproducible bug, or a failing test.238239- A pattern whose force nobody can point to in the code.240- An interface with one implementation, other than a port to an outside241 system, or a factory with one product.242- An observer with one listener in the same module whose reaction must243 happen at once.244- Class names made only of pattern words, such as245 `AppointmentFactoryImpl` or `ChannelDecorator`, on a class whose job246 is a clinic concept.247- The same check or step copied into every implementation of one248 interface.249- Two patterns answering one force in one module.250251## Common mistakes252253- Choosing a pattern because a catalogue lists it, before the code shows254 its force.255- Keeping a pattern after its last variant has gone.256- Adding a class hierarchy where a value or a function would do.257- Naming classes after the pattern instead of the clinic's concept.258- Combining several patterns at once to make a module ready for every259 change.260261## Related skills262263- [oo-design](../oo-design/SKILL.md) sizes a task and defines the rule264 labels.265- [oo-encapsulating-what-varies](../oo-encapsulating-what-varies/SKILL.md)266 finds the seam from evidence before a pattern is added.267- [oo-replacing-conditionals-with-polymorphism](../oo-replacing-conditionals-with-polymorphism/SKILL.md)268 gives a state or a strategy its own objects.269- [oo-choosing-composition-over-inheritance](../oo-choosing-composition-over-inheritance/SKILL.md)270 chooses holding an object over extending it, which a decorator uses.271- [oo-constructing-valid-objects](../oo-constructing-valid-objects/SKILL.md)272 gives a factory or a builder its job.273- [oo-naming-classes-and-methods](../oo-naming-classes-and-methods/SKILL.md)274 keeps a class name on the clinic's concept.275276## Further reading277278- [Patterns by problem](references/patterns-by-problem.md)279- [Patterns beyond objects](references/patterns-beyond-objects.md)