Command

Intent
Put an action and its data inside an object, so whoever triggers it doesn't need to know how it's done and it can be stored, queued, logged or undone.
Application
At the front desk, "book me", "cancel me" or "move me to the seven o'clock" are actions that sometimes need undoing. Turn each one into an object that can be run, undone and written into a history.
Front deskDeskController30ClassRosterFrontDeskService

The front desk asks DeskController to undo, which calls undoLast() on FrontDeskService, highlighted in red; it cancels Leo in ClassRoster.

The diagram doesn't change: FrontDeskService stays highlighted in red and undoLast() fails on an action it doesn't know how to undo.

The Command interface appears, highlighted, with three commands implementing it: BookCommand, CancelCommand and MoveCommand.

BookCommand, highlighted, calls book() or cancel() on ClassRoster.

CancelCommand, highlighted, removes Leo in ClassRoster and keeps his spot, the second one.

FrontDesk, highlighted together with the history, sends execute() to the command and push() to the history.

The Spring context appears. DeskController, highlighted, sends run(commands.book(…)) to FrontDesk, which works with the commands, the history and ClassRoster.

POST /api/desk/undo travels from the front desk to the controller, undo() to FrontDesk, which pops the history; BookCommand, highlighted with FrontDesk, cancels Leo in ClassRoster.

Inside the Spring context, TaskExecutor, highlighted, runs the Runnable lateBooking, also highlighted, with run(); from another thread it asks FrontDesk to run Eva's booking.

Final view: the front desk, the controller, FrontDesk with its history, the three commands and ClassRoster, all inside the Spring context.

Step 1 of 10

"It was Lea, not Leo"

At the front desk, people get booked, cancelled and moved between classes all the time. And sometimes someone gets it wrong: they book Leo into the 18:00 class when it was Lea.

The first version, FrontDeskService, has one method per action (book, cancel, move). To be able to undo, each method writes down by hand what it just did: lastAction, lastSession, lastAthlete, lastSpot… And undoLast() runs a switch on lastAction to know how to revert it.

Step 2 of 10

Only once, and not everything

Look at undoLast()'s limits:

  • It only remembers the last action. If you make two mistakes in a row, the first can no longer be undone.
  • Moving between classes would also need the original class saved: one more field. Meanwhile, move falls into the default and can't be undone.
  • And if tomorrow you can move someone to the waitlist, there's another case to add to the switch.

Step 3 of 10

Each action, an object

Command turns each action into an object with three methods:

  • execute(), do it;
  • undo(), undo it;
  • describe(), tell it in one line for the log.

An object can be stored in a list, handed to someone else, run later or undone. A method can't.

Step 4 of 10

Each command knows how to undo itself

BookCommand keeps its data (class and athlete) and knows how to do and undo:

  • execute() books the athlete in ClassRoster;
  • undo() removes them;
  • describe() says "book Leo into 18:00 WOD".

ClassRoster is the receiver: it knows how to book and remove, but nothing about histories or undoing.

Step 5 of 10

What it takes to go back

Undoing a cancellation isn't just booking again. If Leo was second on the list, he should be second again. That's why CancelCommand saves the spot when it runs, and undo() uses it to put him back in the same place.

MoveCommand does the same across two classes: it books into the new one, removes from the old one saving the spot, and undoing reverses it.

Step 6 of 10

Whoever runs it doesn't know what it runs

FrontDesk is the invoker:

  • run(command) executes it and, if it succeeds, pushes it onto the history and writes it into the log;
  • undo() takes the last one from the history and asks it to undo itself; it only removes it if that works.

It doesn't know whether the command books, cancels or moves. That's why it can undo any number of steps back, and a new command doesn't change a single line of it. The history keeps the last 50.

Step 7 of 10

The controller only creates commands

In Spring, DeskController is the client: with DeskCommands it creates the right command, already validated and wired to ClassRoster, and hands it to FrontDesk.

POST /api/desk/bookings creates a BookCommand; DELETE, a CancelCommand; /moves, a MoveCommand. And POST /api/desk/undo creates nothing: it asks the desk to undo the last thing.

Step 8 of 10

Leo out, Lea in

  1. POST /api/desk/bookings with Leo in class 1: 201 and "done: book Leo into 18:00 WOD" in the log.
  2. POST /api/desk/undo: FrontDesk pops the BookCommand off the history and undoes it; ClassRoster removes Leo.
  3. The answer says what was undone: "book Leo into 18:00 WOD".

If there's nothing left to undo, the answer is 409 "nothing to undo".

Step 9 of 10

Spring already does it for you

Runnable is the minimal version of a command: an action put inside an object, with no undo(). Spring Boot sets up a TaskExecutor, and when you hand it a Runnable it decides when and on which thread to run it. Whoever created it has nothing more to do with running it.

In the example, the Runnable in turn runs a desk command, so that late booking also lands in the history and can be undone.

The same idea shows up elsewhere: with @EnableAsync, @Async turns the call to your method into a task for that same executor (unless you define another one), and TransactionTemplate.execute(...) takes your action to run inside a transaction. But not every callback is a command: a RowMapper, for example, is closer to a Strategy.

Step 10 of 10

Recap

You started with a switch that remembered only the last action and ended up with:

  • Commands, each action in an object that knows how to run, undo and describe itself.
  • A receiver, ClassRoster, that does the work and knows nothing about histories.
  • An invoker, FrontDesk, with a history, a log and multi-step undo.
  • A client, the controller, that only creates commands.

Don't mix it up with its neighbours: Strategy also puts behaviour inside an object, but it's how to do something and it gets swapped; a Command is what to do, with its data, to run now, later or backwards. Memento undoes another way: it saves a snapshot of the state instead of the opposite operation. And with Composite you can bundle several commands into one (a macro) that runs and undoes in one go; MoveCommand is one step away from that.

And when you don't need it: if you'll never undo, queue or log the actions, a method call is simpler; and if you only need to hand an action to someone else, a lambda (Runnable) is usually enough.

Cheatsheet →

Code

FrontDeskService.java

public void undoLast() {
    if (lastAction == null) throw new IllegalStateException("nothing to undo");
    switch (lastAction) {
        case "book" -> roster.cancel(lastSession, lastAthlete);
        case "cancel" -> roster.restore(lastSession, lastSpot, lastAthlete);
        default -> throw new UnsupportedOperationException("can't undo a " + lastAction);
    }
    lastAction = null;                           // and the one before? forgotten
}

FrontDeskService.java

public void undoLast() {
    if (lastAction == null) throw new IllegalStateException("nothing to undo");
    switch (lastAction) {
        case "book" -> roster.cancel(lastSession, lastAthlete);
        case "cancel" -> roster.restore(lastSession, lastSpot, lastAthlete);
        default -> throw new UnsupportedOperationException("can't undo a " + lastAction);
    }
    lastAction = null;                           // and the one before? forgotten
}

Command.java

/** An action at the front desk, packed into an object: it can be run, undone and described. */
public interface Command {
    void execute();
    void undo();
    String describe();
}

BookCommand.java

@Override
public void execute() {
    roster.book(session, athlete);
}

@Override
public void undo() {
    roster.cancel(session, athlete);
}

@Override
public String describe() {
    return "book " + athlete + " into " + roster.name(session);
}

CancelCommand.java

@Override
public void execute() {
    spot = roster.cancel(session, athlete);      // remember where they were…
}

@Override
public void undo() {
    roster.restore(session, spot, athlete);      // …to put them back in the same place
}

FrontDesk.java

public synchronized String run(Command command) {
    command.execute();                          // if it fails, it never reaches the history
    history.push(command);
    if (history.size() > historySize) history.removeLast();
    record("done: " + command.describe());
    return command.describe();
}

public synchronized String undo() {
    if (history.isEmpty()) throw new NothingToUndoException();
    Command last = history.peek();
    last.undo();                                // if undo fails, the command stays in the history
    history.pop();
    record("undone: " + last.describe());
    return last.describe();
}

DeskController.java

@PostMapping("/api/desk/bookings")
@ResponseStatus(HttpStatus.CREATED)
public Map<String, String> book(@RequestBody BookingRequest req) {
    return Map.of("done", desk.run(commands.book(req.session(), req.athlete())));
}

@PostMapping("/api/desk/undo")
public Map<String, String> undo() {
    return Map.of("undone", desk.undo());
}

DeskApiTest.java

mvc.perform(post("/api/desk/bookings").contentType(MediaType.APPLICATION_JSON)
        .content("{\"session\":1,\"athlete\":\"Leo\"}"))
   .andExpect(status().isCreated())
   .andExpect(jsonPath("$.done").value("book Leo into 18:00 WOD"));
mvc.perform(post("/api/desk/undo"))
   .andExpect(status().isOk())
   .andExpect(jsonPath("$.undone").value("book Leo into 18:00 WOD"));

SpringDoesItTooTest.java

Runnable lateBooking = () -> {               // an action packed into an object…
    desk.run(commands.book(2, "Eva"));       // (which runs a desk command, so it can be undone)
    thread.set(Thread.currentThread().getName());
    done.countDown();
};
executor.execute(lateBooking);               // …handed to someone else, who runs it in another thread

Command.java

/** An action at the front desk, packed into an object: it can be run, undone and described. */
public interface Command {
    void execute();
    void undo();
    String describe();
}

Quiz

1. Why does CancelCommand keep the spot the athlete had?

2. What does FrontDesk know about each command it runs?

3. A command fails when it runs because the class is full. What happens to the history?

4. How is a Runnable you hand to a TaskExecutor like a Command?

Cheatsheet →

Run it