State: what each mode allows
Model modes so each action asks the current state whether it is allowed.
Flags do not scale
isMaintenance, isSoldOut, isPaid… Each flag doubles the combinations and every method checks a different subset. Bugs live in the combinations nobody tested.
One state object
Give the object a current state. Each state answers what is allowed and what the next state is. Methods ask the state instead of checking flags.
interface MachineState {
canTakeMoney(): boolean;
canRestock(): boolean;
}
insertCoin(c: number) {
if (!this.state.canTakeMoney()) throw new Error("In maintenance");
this.balance += c;
}
Key takeaways
- Many boolean flags mean hidden states.
- Ask the state, do not check flags.
- A new mode is a new state class.
Hands-on coding exercise
An order moves NEW → PAID → SHIPPED. It can be cancelled while NEW or PAID, never after shipping. Any move that isn't allowed throws.
Write the allowed moves down once, as a table, instead of checking the status in every method.
type Status = "NEW" | "PAID" | "SHIPPED" | "CANCELLED";
class Order {
get status(): Status {
throw new Error("Not implemented");
}
pay(): void {
throw new Error("Not implemented");
}
ship(): void {
throw new Error("Not implemented");
}
cancel(): void {
throw new Error("Not implemented");
}
}
Run your solution against 5 automated tests in the interactive workspace:
Check your understanding
Answer these questions interactively to test what you learned and track progress on your skill map:
- A booking has flags held, confirmed and released. What is the risk?
- With the state pattern, where does "refunds are not allowed in maintenance" live?