intermediate
State
Move state-specific behavior out of conditionals when an object changes behavior across explicit lifecycle states.
State moves behavior tied to lifecycle phases into dedicated state objects, replacing large `switch` statements on status fields. Transitions become explicit methods that swap the active state—orders, tickets, workflows, connection handshakes. It pairs naturally with finite state machines and invalid transition guards.
On interviews: refactor a messy status `if` chain into State classes. Mention table-driven FSMs as an alternative representation.
Common pitfalls: states that mutate context fields inconsistently; transition logic duplicated in UI and backend; unreachable states still representable in types.
The trade-off is flexibility versus complexity—know when the simpler path is enough.
Checklist:
- Each state implements allowed operations only.
- Illegal transitions fail with clear errors.
- Context delegates behavior to current state.
- Diagram or table documents valid transitions.