State and Command Clinic
Retrieval Prompts
- State the three roles in the State pattern and which one drives transitions.
- Name the one axis that distinguishes State from Strategy.
- State the four roles in Command and the directions of dependency.
- Explain why Command makes undo structurally possible.
- Name two problems that appear when you replay a command log against live services.
Compare and Distinguish
- State pattern versus transition-table FSM
- State versus Strategy
- Command versus plain function reference
- undo by inverse versus undo by state snapshot
- in-memory queue versus persistent message broker
Common Mistake Check
- "I used State but each state has five fields of its own that carry over to the next state."
- "We have Command but the
execute()also mutates the Command object itself to record results." - "Redo stack was not cleared when the user did a new action; now redo replays into the wrong state."
- "The job queue runs at-least-once and our
SendEmailhandler is not idempotent." - "The order has a
typeenum and five switches; we introduced State pattern ontype, but it never changes."
Mini Application
Build both in one session:
A. Order Lifecycle with State
- States:
Placed,Paid,Shipped,Delivered,Canceled. - Operations:
pay,ship,deliver,cancel. - Transitions per the concept page.
- Tests: every (state, operation) cell.
- Refactor the previous switch-based version (if you have one) into this State version in small steps, tests green.
B. Text Editor with Commands
- Commands:
Insert,Delete,Replace,UppercaseRange. Historywith capped undo stack of 50 and redo stack.- Coalesce consecutive
Insertinto one logical command when the user types in the same spot. - Macro command: wrap a list; undo in reverse.
- Tests: ten mixed edits + ten undos returns original text.
Cross-Pattern Drill
Combine them:
- In the order lifecycle, commands drive transitions.
PayCommandcallsorder.pay(), which delegates to the state.CancelCommandmust undo -- compensate -- the pay (refund), not reverse the payment's external side effect. - Log every command with a UUID and outcome. Replay the log against a fresh order store and confirm the final state matches.
Evidence Check
This page is complete only if your State-based class has no switch on a status string and your command log replay reproduces the final state exactly.