Command
Definition
Command
- In plain English
- The Command pattern wraps an action and its details in a value, so it can be stored, queued, retried or undone later.
- Think of it like
- It is like writing an order on a ticket and pinning it to the kitchen rail instead of shouting it.
Why it exists
You call a robot’s methods directly. Later, you need to queue requests and reverse a mistaken move.
Represent each request as a value. That value can keep its inputs and the information needed to reverse its effect.
How it works
Undo
- In plain English
- Undo reverses a command's effect using information the command saved.
- Think of it like
- Like a receipt that lets you return exactly what you bought.
Queue
- In plain English
- A queue holds items in order so they can be processed one by one.
- Think of it like
- Like a line at a ticket window.
package commands
import (
"errors"
"fmt"
)
type Command interface {
Execute() error
Undo() error
}
type Robot struct {
Position int
Holding bool
}
type MoveTo struct {
robot *Robot
target, previous int
done bool
}
func (m *MoveTo) Execute() error {
if m.done {
return errors.New("already executed")
}
m.previous = m.robot.Position
m.robot.Position = m.target
m.done = true
return nil
}
func (m *MoveTo) Undo() error {
if !m.done {
return errors.New("nothing to undo")
}
m.robot.Position = m.previous
m.done = false
return nil
}
type Pick struct {
robot *Robot
previous bool
done bool
}
func (p *Pick) Execute() error {
if p.done || p.robot.Holding {
return errors.New("cannot pick")
}
p.previous = p.robot.Holding
p.robot.Holding = true
p.done = true
return nil
}
func (p *Pick) Undo() error {
if !p.done {
return errors.New("nothing to undo")
}
p.robot.Holding = p.previous
p.done = false
return nil
}
func Demo() {
robot := &Robot{}
queue := []Command{&MoveTo{robot: robot, target: 4}, &Pick{robot: robot}}
var history []Command
for _, c := range queue {
if err := c.Execute(); err != nil {
fmt.Println(err)
break
}
history = append(history, c)
}
if len(history) > 0 {
fmt.Println(history[len(history)-1].Undo())
}
fmt.Println(robot.Position)
}
MoveTo and Pick satisfy Command; Controller runs commands through Execute and may request Undo.
- Queues delay execution. History stores successful actions in execution order; undo normally walks that history backward.
- Retry only when repeating an action is safe. Physical actions may succeed even when their acknowledgement is lost.
- Crash replay needs saved action details and a durable log. An in-memory function or slice disappears when the process ends.
Examples
Queue robot actions
MoveTo, Pick and Drop run in order for one robot. A temporary Pick failure receives one retry.
package commands
import (
"errors"
"fmt"
)
type Robot struct {
Position int
Holding bool
failPick bool
}
type Command func() error
func MoveTo(r *Robot, position int) Command {
return func() error { r.Position = position; return nil }
}
func Pick(r *Robot) Command {
return func() error {
if r.failPick {
r.failPick = false
return errors.New("temporary grip failure")
}
r.Holding = true
return nil
}
}
func Drop(r *Robot) Command { return func() error { r.Holding = false; return nil } }
type Job struct {
Name string
Run Command
}
func Demo() {
robot := &Robot{failPick: true}
queue := []Job{{"move", MoveTo(robot, 4)}, {"pick", Pick(robot)}, {"drop", Drop(robot)}}
var log []string
for _, job := range queue {
err := job.Run()
if err != nil {
err = job.Run()
}
if err != nil {
fmt.Println(err)
break
}
log = append(log, job.Name)
}
fmt.Println(log, *robot)
}
The sample failure happens before gripping, so retry is safe. Names alone support inspection; reproducible replay also needs saved inputs and a simulator.
The insight
Actions as values can be queued and recorded.
Cancel before printing
Print jobs wait in a queue. You can cancel a waiting job and retry another job twice after its first failure.
package commands
import (
"errors"
"fmt"
)
type Command func() error
type Job struct {
ID string
Run Command
}
func Cancel(queue []Job, id string) []Job {
out := make([]Job, 0, len(queue))
for _, job := range queue {
if job.ID != id {
out = append(out, job)
}
}
return out
}
func Demo() {
attempts := 0
printJob := func() error {
attempts++
if attempts < 3 {
return errors.New("printer offline")
}
fmt.Println("printed")
return nil
}
queue := []Job{{"poster", printJob}, {"cancelled", func() error { fmt.Println("unwanted print"); return nil }}}
queue = Cancel(queue, "cancelled")
for _, job := range queue {
var err error
for attempt := 0; attempt < 3; attempt++ {
err = job.Run()
if err == nil {
break
}
}
if err != nil {
fmt.Println("failed", job.ID, err)
}
}
}
The stand-in fails before printing. Real retries must avoid duplicate physical output after an uncertain result.
The insight
A queue of commands separates asking from doing.
Reverse a mistaken checkout
Desk staff scan the wrong item. The command saves the previous borrower so Undo can restore it.
package commands
import (
"errors"
"fmt"
)
type Item struct{ Borrower string }
type CheckOut struct {
item *Item
borrower, previous string
done bool
}
func (c *CheckOut) Execute() error {
if c.done || c.item.Borrower != "" {
return errors.New("item unavailable")
}
c.previous = c.item.Borrower
c.item.Borrower = c.borrower
c.done = true
return nil
}
func (c *CheckOut) Undo() error {
if !c.done || c.item.Borrower != c.borrower {
return errors.New("checkout changed or not executed")
}
c.item.Borrower = c.previous
c.done = false
return nil
}
func Demo() {
item := &Item{}
c := &CheckOut{item: item, borrower: "Lee"}
fmt.Println(c.Execute())
fmt.Println(c.Undo())
fmt.Println(item.Borrower)
}
This sequential example permits undo only while the recorded borrower still matches. Real shared stores also need version checks and protected updates.
The insight
Commands that remember their effect make undo possible.
Trade-offs
Pros
- Supports queues and history.
- Actions can carry undo information.
- Separates requesting from execution.
Cons
- More types and bookkeeping.
- Undo must account for later changes.
Use when
- Actions need delayed execution.
- You need controlled retries or reversal.
Avoid when
- An immediate call needs no history.
- A value adds no useful control over execution.
Quick check
Takeaways
- Command turns actions into values.
- That enables queues, retries, logs and undo.
- In Go, a plain func can be a command when undo isn't needed.