Modeling Lifecycles
In this pack:
sizing,
notation,
rule strictness.
Overview
An object that moves through states needs one place that knows how it
moves. Write the states and the transitions out of each down first,
give every transition a method of its own, and let the object refuse a
move its current state does not allow. This skill says where the state
lives, keeps final states final, gives a transition caused by time to
the object, and keeps the history the business asks about.
When to use
- A status field exists and the changes it allows are unclear or
disputed.
- Something cancelled is still started, completed or edited.
- A completed or closed object is reopened and changed.
- A scheduled job changes status, or should.
- The business asks when or why a status changed.
When not to use
- The object has no status, or its status never changes after it is
created. A value or a plain record is enough.
- Fields allow a forbidden combination at one moment, such as accepted
and declined at once, and no move from one status to another is in
question. That is
making illegal states impossible.
- The same switch on a status repeats across methods, and the allowed
transitions are not in question. That is
replacing conditionals with polymorphism.
Core rules
Rule. Write the lifecycle down as its states and, for each state,
the transitions that leave it and what causes each, before coding
it; then give each transition its own method named for it (start,
complete, cancel). A status that callers may set to any value
lets them invent transitions the business never allowed. Keeping
the status without a setter is rule 2 of
encapsulating state and behaviour,
with that rule's exception for a framework that maps fields at the
edge.
Rule. Make the object refuse a transition its current state does
not allow, by raising an error named for the refused transition,
such as AppointmentNotCancellable. Every caller then gets the
same answer without checking the status first, which is rule 3 of
encapsulating state and behaviour.
Judgement. Hold the state in the simplest form the lifecycle
needs: an enumeration field with a check in each transition method
while few methods depend on the state; a status object per state
behind one interface once several methods change with it; a type per
state when callers hold the state itself. An enumeration with a
check in each method is the exception that rule 4 of
replacing conditionals with polymorphism
states for one or two methods; a status object per state is that
rule 4 once several methods change with it; and a type per state is
rule 5 of
making illegal states impossible.
What tips the balance is how many methods change with the state, and
what callers hold.
Rule. Keep a final state final: a cancelled appointment or a
completed visit takes no transition back. Undoing one is either a
transition the business names and allows, with its own method and
rule, such as reopening a visit with a reason within a week, or a
new object, such as a new appointment booked in place of the
cancelled one.
Rule. Give a transition caused by the passing of time to the
object, as a method that is given the time, such as
recordNoShow(now: DateTime), which checks that the slot has
ended. A scheduled job only finds the objects that are due and
sends each the message. The rule stays in one place, and a test can
pass any time, because the clock arrives from outside, as
inverting dependencies
passes a clock.
Judgement. Keep the history of transitions when the business asks
what happened, not only where an object is now: record each
transition with when it happened, who made it and why, either as
data the new state carries (CancellationReason) or as a list of
past transitions. What tips the balance is whether anyone, such as
a patient, an auditor or a report, asks when or why a state changed.
When nobody does, the current state is enough.
Pattern
Before, Appointment has setStatus, so any caller can move it to any
status: ConsultationScreen.finish completes an appointment that never
started, nothing stops a caller from setting Scheduled back on a
cancelled booking, and a booking can reach Cancelled without its slot
being released. After, every transition is a method of its own, the
appointment refuses a move its state does not allow, and the screen asks
for the move it means.
The AppointmentStatus in these fences adds InProgress and
Completed to the notation's Scheduled and Cancelled.
Before:
enum AppointmentStatus
Scheduled
InProgress
Completed
Cancelled
class Appointment
- slot: Slot
- patient: PatientId
- status: AppointmentStatus
- new(slot: Slot, patient: PatientId, status: AppointmentStatus)
+ static book(slot: Slot, patient: PatientId): Appointment
slot.reserve(patient)
return new Appointment(slot, patient, Scheduled)
+ setStatus(newStatus: AppointmentStatus): void
status := newStatus
return
+ cancel(reason: CancellationReason): void
raises AppointmentNotCancellable
if status = Scheduled then
status := Cancelled
slot.release(patient)
else
raise AppointmentNotCancellable
return
class ConsultationScreen
+ finish(appointment: Appointment): void
appointment.setStatus(Completed)
return
book reserves the slot once and builds the appointment through the
private constructor, which sets slot, patient and status. cancel
releases the slot once. setStatus assigns whatever status it is
given, so finish completes an appointment that was never started.
After:
The lifecycle has only these moves, and a move a state refuses raises
the error named for it.
| State |
Move |
Goes to |
A refusal raises |
| Scheduled |
start |
InProgress |
AppointmentNotStartable |
| Scheduled |
cancel |
Cancelled |
AppointmentNotCancellable |
| InProgress |
complete |
Completed |
AppointmentNotCompletable |
| Completed |
start, complete, cancel |
nothing |
each error above |
| Cancelled |
start, complete, cancel |
nothing |
each error above |
A move asked of a state that does not list it is refused with the error
named for that move. Completed and Cancelled refuse all three.
enum AppointmentStatus
Scheduled
InProgress
Completed
Cancelled
class Appointment
- slot: Slot
- patient: PatientId
- status: AppointmentStatus
- new(slot: Slot, patient: PatientId, status: AppointmentStatus)
+ static book(slot: Slot, patient: PatientId): Appointment
slot.reserve(patient)
return new Appointment(slot, patient, Scheduled)
+ start(): void
raises AppointmentNotStartable
if status = Scheduled then
status := InProgress
else
raise AppointmentNotStartable
return
+ complete(): void
raises AppointmentNotCompletable
if status = InProgress then
status := Completed
else
raise AppointmentNotCompletable
return
+ cancel(reason: CancellationReason): void
raises AppointmentNotCancellable
if status = Scheduled then
status := Cancelled
slot.release(patient)
else
raise AppointmentNotCancellable
return
class ConsultationScreen
+ begin(appointment: Appointment): void
appointment.start()
return
+ finish(appointment: Appointment): void
appointment.complete()
return
After, Appointment has no setStatus. start accepts only
Scheduled, complete only InProgress, and cancel only
Scheduled; each raises the error named for it in every other state.
In this fence, book is still the only way to make an appointment,
because the constructor is private. ConsultationScreen.begin sends
start(), and finish sends complete(), so the screen never reads
the status and a cancelled or completed appointment refuses both. Each
transition changes the status once, book reserves the slot once, and
cancel releases it once.
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 public method that sets the status to whatever value a caller
passes.
- Callers that check the status before every change they make.
- A final status, such as cancelled or completed, that some path
changes back.
- A scheduled job that writes status fields itself, with its own copy
of the rule.
- A status that nothing ever enters.
- A status that nothing ever leaves, where the business does not treat
it as the end.
Common mistakes
- Adding a state to the enumeration and coding the moves into it
without writing down which transitions enter and leave it.
- Checking the allowed transitions in every caller instead of in the
object.
- Reopening a final state by assigning the old status back, instead of
naming the transition and its rule.
- Moving to a status object per state for a lifecycle that one or two
methods depend on.
- Losing when and why a transition happened, until the business asks.
Related skills
Further reading
- Transition tables
- Time and history
1---2name: oo-modeling-lifecycles3description: Use when deciding which status transitions are allowed, when something cancelled can still go ahead, or a closed one is reopened and edited.4license: MIT5metadata:6 source: https://skillmd.com/skills/yutna/oo-modeling-lifecycles7 version: 0.21.08 pack: object-oriented-design-skills9---1011# Modeling Lifecycles1213**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## Overview1920An object that moves through states needs one place that knows how it21moves. Write the states and the transitions out of each down first,22give every transition a method of its own, and let the object refuse a23move its current state does not allow. This skill says where the state24lives, keeps final states final, gives a transition caused by time to25the object, and keeps the history the business asks about.2627## When to use2829- A status field exists and the changes it allows are unclear or30 disputed.31- Something cancelled is still started, completed or edited.32- A completed or closed object is reopened and changed.33- A scheduled job changes status, or should.34- The business asks when or why a status changed.3536## When not to use3738- The object has no status, or its status never changes after it is39 created. A value or a plain record is enough.40- Fields allow a forbidden combination at one moment, such as accepted41 and declined at once, and no move from one status to another is in42 question. That is43 [making illegal states impossible](../oo-making-illegal-states-impossible/SKILL.md).44- The same switch on a status repeats across methods, and the allowed45 transitions are not in question. That is46 [replacing conditionals with polymorphism](../oo-replacing-conditionals-with-polymorphism/SKILL.md).4748## Core rules49501. Rule. **Write the lifecycle down as its states and, for each state,51 the transitions that leave it and what causes each, before coding52 it; then give each transition its own method named for it (`start`,53 `complete`, `cancel`).** A status that callers may set to any value54 lets them invent transitions the business never allowed. Keeping55 the status without a setter is rule 2 of56 [encapsulating state and behaviour](../oo-encapsulating-state-and-behaviour/SKILL.md),57 with that rule's exception for a framework that maps fields at the58 edge.59602. Rule. **Make the object refuse a transition its current state does61 not allow, by raising an error named for the refused transition,62 such as `AppointmentNotCancellable`.** Every caller then gets the63 same answer without checking the status first, which is rule 3 of64 [encapsulating state and behaviour](../oo-encapsulating-state-and-behaviour/SKILL.md).65663. Judgement. **Hold the state in the simplest form the lifecycle67 needs: an enumeration field with a check in each transition method68 while few methods depend on the state; a status object per state69 behind one interface once several methods change with it; a type per70 state when callers hold the state itself.** An enumeration with a71 check in each method is the exception that rule 4 of72 [replacing conditionals with polymorphism](../oo-replacing-conditionals-with-polymorphism/SKILL.md)73 states for one or two methods; a status object per state is that74 rule 4 once several methods change with it; and a type per state is75 rule 5 of76 [making illegal states impossible](../oo-making-illegal-states-impossible/SKILL.md).77 What tips the balance is how many methods change with the state, and78 what callers hold.79804. Rule. **Keep a final state final: a cancelled appointment or a81 completed visit takes no transition back.** Undoing one is either a82 transition the business names and allows, with its own method and83 rule, such as reopening a visit with a reason within a week, or a84 new object, such as a new appointment booked in place of the85 cancelled one.86875. Rule. **Give a transition caused by the passing of time to the88 object, as a method that is given the time, such as89 `recordNoShow(now: DateTime)`, which checks that the slot has90 ended.** A scheduled job only finds the objects that are due and91 sends each the message. The rule stays in one place, and a test can92 pass any time, because the clock arrives from outside, as93 [inverting dependencies](../oo-inverting-dependencies/SKILL.md)94 passes a clock.95966. Judgement. **Keep the history of transitions when the business asks97 what happened, not only where an object is now: record each98 transition with when it happened, who made it and why, either as99 data the new state carries (`CancellationReason`) or as a list of100 past transitions.** What tips the balance is whether anyone, such as101 a patient, an auditor or a report, asks when or why a state changed.102 When nobody does, the current state is enough.103104## Pattern105106Before, `Appointment` has `setStatus`, so any caller can move it to any107status: `ConsultationScreen.finish` completes an appointment that never108started, nothing stops a caller from setting `Scheduled` back on a109cancelled booking, and a booking can reach `Cancelled` without its slot110being released. After, every transition is a method of its own, the111appointment refuses a move its state does not allow, and the screen asks112for the move it means.113114The `AppointmentStatus` in these fences adds `InProgress` and115`Completed` to the notation's `Scheduled` and `Cancelled`.116117Before:118119```text120enum AppointmentStatus121 Scheduled122 InProgress123 Completed124 Cancelled125126class Appointment127 - slot: Slot128 - patient: PatientId129 - status: AppointmentStatus130 - new(slot: Slot, patient: PatientId, status: AppointmentStatus)131 + static book(slot: Slot, patient: PatientId): Appointment132 slot.reserve(patient)133 return new Appointment(slot, patient, Scheduled)134 + setStatus(newStatus: AppointmentStatus): void135 status := newStatus136 return137 + cancel(reason: CancellationReason): void138 raises AppointmentNotCancellable139 if status = Scheduled then140 status := Cancelled141 slot.release(patient)142 else143 raise AppointmentNotCancellable144 return145146class ConsultationScreen147 + finish(appointment: Appointment): void148 appointment.setStatus(Completed)149 return150```151152`book` reserves the slot once and builds the appointment through the153private constructor, which sets `slot`, `patient` and `status`. `cancel`154releases the slot once. `setStatus` assigns whatever status it is155given, so `finish` completes an appointment that was never started.156157After:158159The lifecycle has only these moves, and a move a state refuses raises160the error named for it.161162|State|Move|Goes to|A refusal raises|163|---|---|---|---|164|Scheduled|start|InProgress|`AppointmentNotStartable`|165|Scheduled|cancel|Cancelled|`AppointmentNotCancellable`|166|InProgress|complete|Completed|`AppointmentNotCompletable`|167|Completed|start, complete, cancel|nothing|each error above|168|Cancelled|start, complete, cancel|nothing|each error above|169170A move asked of a state that does not list it is refused with the error171named for that move. `Completed` and `Cancelled` refuse all three.172173```text174enum AppointmentStatus175 Scheduled176 InProgress177 Completed178 Cancelled179180class Appointment181 - slot: Slot182 - patient: PatientId183 - status: AppointmentStatus184 - new(slot: Slot, patient: PatientId, status: AppointmentStatus)185 + static book(slot: Slot, patient: PatientId): Appointment186 slot.reserve(patient)187 return new Appointment(slot, patient, Scheduled)188 + start(): void189 raises AppointmentNotStartable190 if status = Scheduled then191 status := InProgress192 else193 raise AppointmentNotStartable194 return195 + complete(): void196 raises AppointmentNotCompletable197 if status = InProgress then198 status := Completed199 else200 raise AppointmentNotCompletable201 return202 + cancel(reason: CancellationReason): void203 raises AppointmentNotCancellable204 if status = Scheduled then205 status := Cancelled206 slot.release(patient)207 else208 raise AppointmentNotCancellable209 return210211class ConsultationScreen212 + begin(appointment: Appointment): void213 appointment.start()214 return215 + finish(appointment: Appointment): void216 appointment.complete()217 return218```219220After, `Appointment` has no `setStatus`. `start` accepts only221`Scheduled`, `complete` only `InProgress`, and `cancel` only222`Scheduled`; each raises the error named for it in every other state.223In this fence, `book` is still the only way to make an appointment,224because the constructor is private. `ConsultationScreen.begin` sends225`start()`, and `finish` sends `complete()`, so the screen never reads226the status and a cancelled or completed appointment refuses both. Each227transition changes the status once, `book` reserves the slot once, and228`cancel` releases it once.229230## Red flags231232Places to look, not verdicts. A red flag becomes a finding only with233evidence: a measurement, a reproducible bug, or a failing test.234235- A public method that sets the status to whatever value a caller236 passes.237- Callers that check the status before every change they make.238- A final status, such as cancelled or completed, that some path239 changes back.240- A scheduled job that writes status fields itself, with its own copy241 of the rule.242- A status that nothing ever enters.243- A status that nothing ever leaves, where the business does not treat244 it as the end.245246## Common mistakes247248- Adding a state to the enumeration and coding the moves into it249 without writing down which transitions enter and leave it.250- Checking the allowed transitions in every caller instead of in the251 object.252- Reopening a final state by assigning the old status back, instead of253 naming the transition and its rule.254- Moving to a status object per state for a lifecycle that one or two255 methods depend on.256- Losing when and why a transition happened, until the business asks.257258## Related skills259260- [oo-design](../oo-design/SKILL.md) sizes a task and defines the rule261 labels.262- [oo-encapsulating-state-and-behaviour](../oo-encapsulating-state-and-behaviour/SKILL.md)263 tells a caller to send the action instead of reading the state.264- [oo-replacing-conditionals-with-polymorphism](../oo-replacing-conditionals-with-polymorphism/SKILL.md)265 gives each status its own object when several methods change with it.266- [oo-making-illegal-states-impossible](../oo-making-illegal-states-impossible/SKILL.md)267 gives each state its own type when callers hold the state.268269## Further reading270271- [Transition tables](references/transition-tables.md)272- [Time and history](references/time-and-history.md)