Skip to main content

State and Command Clinic

Retrieval Prompts

  1. State the three roles in the State pattern and which one drives transitions.
  2. Name the one axis that distinguishes State from Strategy.
  3. State the four roles in Command and the directions of dependency.
  4. Explain why Command makes undo structurally possible.
  5. 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

  1. "I used State but each state has five fields of its own that carry over to the next state."
  2. "We have Command but the execute() also mutates the Command object itself to record results."
  3. "Redo stack was not cleared when the user did a new action; now redo replays into the wrong state."
  4. "The job queue runs at-least-once and our SendEmail handler is not idempotent."
  5. "The order has a type enum and five switches; we introduced State pattern on type, but it never changes."

Mini Application

Build both in one session:

A. Order Lifecycle with State

  1. States: Placed, Paid, Shipped, Delivered, Canceled.
  2. Operations: pay, ship, deliver, cancel.
  3. Transitions per the concept page.
  4. Tests: every (state, operation) cell.
  5. Refactor the previous switch-based version (if you have one) into this State version in small steps, tests green.

B. Text Editor with Commands

  1. Commands: Insert, Delete, Replace, UppercaseRange.
  2. History with capped undo stack of 50 and redo stack.
  3. Coalesce consecutive Insert into one logical command when the user types in the same spot.
  4. Macro command: wrap a list; undo in reverse.
  5. Tests: ten mixed edits + ten undos returns original text.

Cross-Pattern Drill

Combine them:

  • In the order lifecycle, commands drive transitions. PayCommand calls order.pay(), which delegates to the state. CancelCommand must 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.