Command
Intent
Wrap each request as an object holding everything needed to run it, so calls can be queued, logged, and undone.
Motivation
A TV remote has on, off, and undo buttons. Wiring the remote directly to lamp circuits means every new device rewrites the remote. Turning each press into a command object — one for “light on”, one for “light off” — lets the remote store, replay, and reverse presses without knowing what a light is.
Structure
flowchart LR Remote[Remote Invoker] --> Cmd[Command] Cmd --> OnCmd[LightOn Command] Cmd --> OffCmd[LightOff Command] OnCmd --> Light[Light Receiver] OffCmd --> Light
- Invoker (Remote) — holds commands and triggers them; keeps history for undo.
- Command (LightOn, LightOff) — packages one request plus its undo step.
- Receiver (Light) — the device that actually does the work when a command runs.
Consequences
- Benefit: requests become storable values — queueable, loggable, replayable, and undoable.
- Cost: one small class per action; simple calls gain indirection that can feel heavy.
Basic Recap
Command turns a request into an object containing the action and the data needed to perform it. Invokers can queue, schedule, log, or route commands without knowing receiver details. Receivers implement the actual work, while command handlers connect the two. Undo is possible only when the domain offers a real inverse or compensation; storing an object does not automatically make its effects reversible.
Complex Scenario
A deployment platform represents scale, restart, and configuration-change requests as commands placed on a durable work queue. The API validates and serializes intent, the scheduler chooses a worker, and a handler invokes the infrastructure receiver. Operators can inspect pending requests and cancel work that has not started. Each command carries a stable identifier, target version, and authorization context captured at submission time.
Edge cases
- Retries: Queue redelivery after worker failure must not scale a service twice, so handlers use idempotency records or reconcile actual target state.
- Ordering: A restart submitted before a configuration change may be invalid after it; target versions and per-target sequencing prevent stale commands from overtaking newer intent.
- Memory pressure: A durable backlog should store compact payloads and claim work in batches rather than loading every pending command into worker memory.
A user-facing undo operation should issue a new compensating command with its own policy and audit record, not blindly replay mutable receiver state. Queue persistence also needs an explicit retention policy for authorization data and payloads that may contain sensitive configuration.
Sketch (illustrative pseudocode, not runnable):
worker.claimBatch(limit):
for command in batch:
if command.targetVersion < currentVersion(command.target):
markSuperseded(command)
continue
execution = executions.beginOrLoad(command.id)
if not execution.completed:
result = registry.handler(command.type).handle(command)
executions.completeOnce(command.id, result)
acknowledgeAfterDurablyRecording(command)
When to Use / When Not to Use
Use when:
- Actions need undo, redo, queuing, scheduling, or logging.
- The sender of a request should not depend on the receiver’s type.
Avoid when:
- Every call is fire-and-forget with no history need — a plain function call is simpler.
Examples
examples/elixir/command/examples/dart/command/examples/go/command/examples/rust/command/
Expected outcome: pressing on prints the light is ON, then undo prints it is OFF again.
Anti-pattern / Failure Mode
-
Misuse: Commands as glorified function calls with no queue, log, or undo need.
-
Review signal: Command classes with one method that only forwards — indirection without benefit.
-
Misuse symptom: One command class contains a giant type switch and all receiver logic, recreating procedural dispatch behind a fashionable name. Serializing live services, credentials, or open connections into queued commands is another failure that makes replay unsafe.
-
Review signal: Look for commands without stable identifiers, handlers with non-idempotent external calls, and
undomethods that assume external systems have not changed. Queue metrics should distinguish duplicate delivery from new submissions; a lack of execution records makes retries impossible to audit.
Related
- Memento — commands plus snapshots enable undo.
- Strategy — requests as objects vs swappable steps.
- Order Pipeline — commands separate payment variants from refunds.
Exercise
Add a dim command that sets brightness to 50 and undoes back to the previous level. Store enough prior state in the command to make undo exact.
Self-check
- Where does undo knowledge live?
Answer
In each command object, which captures the prior state or the inverse action — not in the remote or the light. - What does the invoker know about the receiver?
Answer
Nothing — it only knows the command interface, so new devices plug in without touching the remote. - Command vs Strategy: what differs?
Answer
Strategy swaps one step of an algorithm; Command packages a full request with context so it can be stored and reversed later.