Making Illegal States Impossible
In this pack:
sizing,
notation,
rule strictness.
Overview
A type should allow exactly the values the domain has. A class that
carries a boolean per stage and an optional field per stage detail
multiplies those possibilities: three optional fields allow eight
combinations for a prescription with four states, and nothing in the
type says which combinations are real. This skill replaces the flags
with one type per state, each holding only that state's data, closes
the set where the domain closes it, and moves rules into the types that
can enforce them. An action then exists only on the state that allows
it, so an impossible combination has no way to be built.
When to use
- Two or more booleans on one class describe stages of one lifecycle.
- An optional field is set only in some states, or a comment beside the
fields says "never both".
- A method opens by rejecting a combination that should never exist.
- A type admits values the domain never has, such as an appointment
request that is accepted and declined at once.
- A rule that only reads a value's own fields is checked at every call
site instead of once, when the value is built.
- A stored record holds a combination the code calls impossible.
- A new state arrives, and every place that branches on the old fields
must be found by hand.
When not to use
Core rules
Rule. Make every value a type allows a state the domain allows.
When flags and optional fields are meaningful only in some
combinations, replace them with one type per real state. Each type
holds exactly the data its state has, and no other state's data. The
type then has no value that stands for a state the clinic never has.
Rule. Close the set of states where the domain closes it. Mark
the state types as a closed set; in the notation a -- comment does
that, and the language packs name the keyword. A new state is then a
deliberate edit to the set, and every exhaustive test over the set
must handle it before the code builds.
Default. Carry a rule in a type before writing a check for it. A
duration that cannot be negative, or a time range whose end follows
its start, is built only through a constructor that refuses a broken
value. Every holder then knows the rule holds, and no call site
repeats it.
The exception is a rule that depends on other objects or on time,
such as whether a slot is free now. Check it where the action
happens.
Judgement. Choose between an enumeration and a class per state by
the data the states carry. States that carry the same data, or no
data, fit an enumeration, with behaviour per member where the
language allows it. States that carry different data need a class
each. What tips the balance is whether any state has a field the
others lack.
Judgement. Offer an action only on the state that allows it when
callers hold the state itself. When callers hold the entity and its
status changes over its life, keep a status object inside the entity
and replace the conditionals with polymorphism. What tips the balance
is what the caller holds: with the state in hand, an action the state
lacks is a message its type does not answer, not a check that fails
at run time.
Default. Make each state's data required. A field that is
optional only because some states lack it belongs to the types of the
states that have it. The state that has the field then always has a
value for it.
The exception is a field the domain treats as optional in every
state, such as a free-text note.
Pattern
Before, Prescription holds three optional fields beside the three
that every prescription has. The optional fields allow eight
combinations, while a prescription has four states, and nothing stops
dispense on one nobody issued or cancel on one already dispensed.
Before:
class Prescription
- id: PrescriptionId
- patient: PatientId
- medicine: Medicine
- issuedBy: ClinicianId?
- dispensedOn: Date?
- cancelReason: CancellationReason?
+ new(id: PrescriptionId, patient: PatientId, medicine: Medicine)
issuedBy := null
dispensedOn := null
cancelReason := null
+ issue(by: ClinicianId): void
issuedBy := by
return
+ dispense(on: Date): void
dispensedOn := on
return
+ cancel(reason: CancellationReason): void
cancelReason := reason
return
After, four values form a closed set behind interface Prescription.
Each holds only its own state's data, every field is required, and the
three actions each return a new value.
After:
interface Prescription
-- closed: these four states are the only prescriptions
+ medicine(): Medicine
value DraftPrescription implements Prescription
- id: PrescriptionId
- patient: PatientId
- medicine: Medicine
+ new(id: PrescriptionId, patient: PatientId, medicine: Medicine)
+ medicine(): Medicine
return medicine
+ issue(by: ClinicianId): IssuedPrescription
return new IssuedPrescription(id, patient, medicine, by)
value IssuedPrescription implements Prescription
- id: PrescriptionId
- patient: PatientId
- medicine: Medicine
- issuedBy: ClinicianId
+ new(id: PrescriptionId, patient: PatientId, medicine: Medicine,
issuedBy: ClinicianId)
+ medicine(): Medicine
return medicine
+ dispense(on: Date): DispensedPrescription
return new DispensedPrescription(id, patient, medicine, issuedBy, on)
+ cancel(reason: CancellationReason): CancelledPrescription
return new CancelledPrescription(id, patient, medicine, issuedBy,
reason)
value DispensedPrescription implements Prescription
- id: PrescriptionId
- patient: PatientId
- medicine: Medicine
- issuedBy: ClinicianId
- dispensedOn: Date
+ new(id: PrescriptionId, patient: PatientId, medicine: Medicine,
issuedBy: ClinicianId, dispensedOn: Date)
+ medicine(): Medicine
return medicine
value CancelledPrescription implements Prescription
- id: PrescriptionId
- patient: PatientId
- medicine: Medicine
- issuedBy: ClinicianId
- reason: CancellationReason
+ new(id: PrescriptionId, patient: PatientId, medicine: Medicine,
issuedBy: ClinicianId, reason: CancellationReason)
+ medicine(): Medicine
return medicine
The identifier id keeps two prescriptions two prescriptions when
they share a patient and a medicine, as the values skill's rules 1 and
4 require. medicine() answers the one field every state holds.
issue returns an IssuedPrescription, dispense a
DispensedPrescription, and cancel a CancelledPrescription; no
method assigns to a field, so no state changes after its constructor.
DraftPrescription offers issue as its only action,
IssuedPrescription offers dispense and cancel, and the two end
states offer neither dispense nor cancel, so a message a state does
not allow has no method to land on. The -- comment marks the set
closed. The constructor parameters are named for their fields, so each
constructor sets every field before any action reads it.
CancellationReason is the notation's value for why an appointment was
cancelled, and the same value serves a prescription here. The
constructing skill's builder holds a Prescription as one optional part
of a report; here the same name is the interface over the four states.
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.
- Two or more booleans on one class that describe one lifecycle.
- An optional field that is set only in some states.
- A check at the top of a method for a combination that should never
happen.
- A comment such as "never both" or "only when cancelled" beside
fields.
- An enumeration member that needs data the other members lack.
Common mistakes
- Adding a check for an impossible combination instead of removing the
combination.
- A class per state for states that carry the same data, where an
enumeration says it.
- Leaving the set of states open, so a new state skips the places that
must handle it.
- Giving a state type a setter that turns it into another state.
- Putting a rule about other objects or about time into a type, where
it goes stale.
Related skills
Further reading
- States as types
- Rules in types
1---2name: oo-making-illegal-states-impossible3description: Use when flags or optional fields allow forbidden states, such as accepted and declined at once, or a reason set when nothing was cancelled.4license: MIT5metadata:6 source: https://skillmd.com/skills/yutna/oo-making-illegal-states-impossible7 version: 0.21.08 pack: object-oriented-design-skills9---1011# Making Illegal States Impossible1213**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 type should allow exactly the values the domain has. A class that21carries a boolean per stage and an optional field per stage detail22multiplies those possibilities: three optional fields allow eight23combinations for a prescription with four states, and nothing in the24type says which combinations are real. This skill replaces the flags25with one type per state, each holding only that state's data, closes26the set where the domain closes it, and moves rules into the types that27can enforce them. An action then exists only on the state that allows28it, so an impossible combination has no way to be built.2930## When to use3132- Two or more booleans on one class describe stages of one lifecycle.33- An optional field is set only in some states, or a comment beside the34 fields says "never both".35- A method opens by rejecting a combination that should never exist.36- A type admits values the domain never has, such as an appointment37 request that is accepted and declined at once.38- A rule that only reads a value's own fields is checked at every call39 site instead of once, when the value is built.40- A stored record holds a combination the code calls impossible.41- A new state arrives, and every place that branches on the old fields42 must be found by hand.4344## When not to use4546- The rule depends on other objects or on time, such as whether a slot47 is free now. Check it where the action happens, as48 [encapsulating state and behaviour](../oo-encapsulating-state-and-behaviour/SKILL.md)49 describes.50- The question is how to build an object whose states are already51 settled, with a constructor, a factory or a builder. That belongs to52 [constructing valid objects](../oo-constructing-valid-objects/SKILL.md).53- The cases differ in behaviour, and the question is whether to use54 subtypes or exhaustive matching as kinds and operations grow. That is55 [replacing conditionals with polymorphism](../oo-replacing-conditionals-with-polymorphism/SKILL.md).56- The data crosses a process boundary as a plain record. That is57 [deciding object or data](../oo-deciding-object-or-data/SKILL.md).5859## Core rules60611. Rule. **Make every value a type allows a state the domain allows.**62 When flags and optional fields are meaningful only in some63 combinations, replace them with one type per real state. Each type64 holds exactly the data its state has, and no other state's data. The65 type then has no value that stands for a state the clinic never has.66672. Rule. **Close the set of states where the domain closes it.** Mark68 the state types as a closed set; in the notation a `--` comment does69 that, and the language packs name the keyword. A new state is then a70 deliberate edit to the set, and every exhaustive test over the set71 must handle it before the code builds.72733. Default. **Carry a rule in a type before writing a check for it.** A74 duration that cannot be negative, or a time range whose end follows75 its start, is built only through a constructor that refuses a broken76 value. Every holder then knows the rule holds, and no call site77 repeats it.7879 The exception is a rule that depends on other objects or on time,80 such as whether a slot is free now. Check it where the action81 happens.82834. Judgement. **Choose between an enumeration and a class per state by84 the data the states carry.** States that carry the same data, or no85 data, fit an enumeration, with behaviour per member where the86 language allows it. States that carry different data need a class87 each. What tips the balance is whether any state has a field the88 others lack.89905. Judgement. **Offer an action only on the state that allows it when91 callers hold the state itself.** When callers hold the entity and its92 status changes over its life, keep a status object inside the entity93 and replace the conditionals with polymorphism. What tips the balance94 is what the caller holds: with the state in hand, an action the state95 lacks is a message its type does not answer, not a check that fails96 at run time.97986. Default. **Make each state's data required.** A field that is99 optional only because some states lack it belongs to the types of the100 states that have it. The state that has the field then always has a101 value for it.102103 The exception is a field the domain treats as optional in every104 state, such as a free-text note.105106## Pattern107108Before, `Prescription` holds three optional fields beside the three109that every prescription has. The optional fields allow eight110combinations, while a prescription has four states, and nothing stops111`dispense` on one nobody issued or `cancel` on one already dispensed.112113Before:114115```text116class Prescription117 - id: PrescriptionId118 - patient: PatientId119 - medicine: Medicine120 - issuedBy: ClinicianId?121 - dispensedOn: Date?122 - cancelReason: CancellationReason?123 + new(id: PrescriptionId, patient: PatientId, medicine: Medicine)124 issuedBy := null125 dispensedOn := null126 cancelReason := null127 + issue(by: ClinicianId): void128 issuedBy := by129 return130 + dispense(on: Date): void131 dispensedOn := on132 return133 + cancel(reason: CancellationReason): void134 cancelReason := reason135 return136```137138After, four values form a closed set behind `interface Prescription`.139Each holds only its own state's data, every field is required, and the140three actions each return a new value.141142After:143144```text145interface Prescription146 -- closed: these four states are the only prescriptions147 + medicine(): Medicine148149value DraftPrescription implements Prescription150 - id: PrescriptionId151 - patient: PatientId152 - medicine: Medicine153 + new(id: PrescriptionId, patient: PatientId, medicine: Medicine)154 + medicine(): Medicine155 return medicine156 + issue(by: ClinicianId): IssuedPrescription157 return new IssuedPrescription(id, patient, medicine, by)158159value IssuedPrescription implements Prescription160 - id: PrescriptionId161 - patient: PatientId162 - medicine: Medicine163 - issuedBy: ClinicianId164 + new(id: PrescriptionId, patient: PatientId, medicine: Medicine,165 issuedBy: ClinicianId)166 + medicine(): Medicine167 return medicine168 + dispense(on: Date): DispensedPrescription169 return new DispensedPrescription(id, patient, medicine, issuedBy, on)170 + cancel(reason: CancellationReason): CancelledPrescription171 return new CancelledPrescription(id, patient, medicine, issuedBy,172 reason)173174value DispensedPrescription implements Prescription175 - id: PrescriptionId176 - patient: PatientId177 - medicine: Medicine178 - issuedBy: ClinicianId179 - dispensedOn: Date180 + new(id: PrescriptionId, patient: PatientId, medicine: Medicine,181 issuedBy: ClinicianId, dispensedOn: Date)182 + medicine(): Medicine183 return medicine184185value CancelledPrescription implements Prescription186 - id: PrescriptionId187 - patient: PatientId188 - medicine: Medicine189 - issuedBy: ClinicianId190 - reason: CancellationReason191 + new(id: PrescriptionId, patient: PatientId, medicine: Medicine,192 issuedBy: ClinicianId, reason: CancellationReason)193 + medicine(): Medicine194 return medicine195```196197The identifier `id` keeps two prescriptions two prescriptions when198they share a patient and a medicine, as the values skill's rules 1 and1994 require. `medicine()` answers the one field every state holds.200`issue` returns an `IssuedPrescription`, `dispense` a201`DispensedPrescription`, and `cancel` a `CancelledPrescription`; no202method assigns to a field, so no state changes after its constructor.203`DraftPrescription` offers `issue` as its only action,204`IssuedPrescription` offers `dispense` and `cancel`, and the two end205states offer neither `dispense` nor `cancel`, so a message a state does206not allow has no method to land on. The `--` comment marks the set207closed. The constructor parameters are named for their fields, so each208constructor sets every field before any action reads it.209`CancellationReason` is the notation's value for why an appointment was210cancelled, and the same value serves a prescription here. The211constructing skill's builder holds a `Prescription` as one optional part212of a report; here the same name is the interface over the four states.213214## Red flags215216Places to look, not verdicts. A red flag becomes a finding only with217evidence: a measurement, a reproducible bug, or a failing test.218219- Two or more booleans on one class that describe one lifecycle.220- An optional field that is set only in some states.221- A check at the top of a method for a combination that should never222 happen.223- A comment such as "never both" or "only when cancelled" beside224 fields.225- An enumeration member that needs data the other members lack.226227## Common mistakes228229- Adding a check for an impossible combination instead of removing the230 combination.231- A class per state for states that carry the same data, where an232 enumeration says it.233- Leaving the set of states open, so a new state skips the places that234 must handle it.235- Giving a state type a setter that turns it into another state.236- Putting a rule about other objects or about time into a type, where237 it goes stale.238239## Related skills240241- [oo-design](../oo-design/SKILL.md) sizes a task and defines the rule242 labels.243- [oo-constructing-valid-objects](../oo-constructing-valid-objects/SKILL.md)244 builds the object once its shape is chosen.245- [oo-modeling-values-and-entities](../oo-modeling-values-and-entities/SKILL.md)246 keeps the identifier and the value immutable.247- [oo-replacing-conditionals-with-polymorphism](../oo-replacing-conditionals-with-polymorphism/SKILL.md)248 gives a status object to an entity whose status changes.249250## Further reading251252- [States as types](references/states-as-types.md)253- [Rules in types](references/rules-in-types.md)