System Design Academy

Saving…

Lesson 10 of 11 in Module 30 of 45 lessons complete

Command

Module 3, lesson 10Concept12 min

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.
Complete library with Demo: moveTo and Pick commands save their prior values for undo.
Go
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.

The controller uses the command contract.

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.

Complete library with Demo: queue robot actions.
Go
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.

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

You need to queue robot actions, retry failures and replay a day's work. Which pattern?
What must a command keep in order to support Undo?

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.

Try the quick check above whenever you feel ready.

Previous: State