Memento

Intent
Save an object's state in an opaque snapshot so you can go back to it later, without whoever keeps it having to know or touch the inner details.
Application
The coach drafts the whiteboard WOD and sometimes wipes what she shouldn't. Save snapshots of the draft without opening its fields to anyone, and undo by going back to the last one.
ExposedDraft (getters + setters)DraftControllerExposedDraftEditor

ExposedDraftEditor reads getTitle() and getMovements() from ExposedDraft, which exposes all its fields; both are highlighted.

ExposedDraftEditor, highlighted: it saves the title and movements, but the time cap is left uncopied.

WhiteboardDraft and a Snapshot, highlighted: the draft calls snapshot() and gets its frozen copy.

DraftHistory, highlighted, stacks snapshots with push() and hands back the last one with pop().

DraftService, highlighted, calls snapshot() and edit() on the draft and save() on the history.

WhiteboardDraft and the Snapshot, highlighted: restore() brings the draft back to the saved state.

POST /api/draft/undo travels from the coach to the controller, then undo() to the service, which asks the history for the snapshot and restores it in the draft; DraftService and DraftHistory are highlighted.

TransactionStatus, highlighted, creates a savepoint, also highlighted, and then goes back to it after a wrong insert into the pr table.

Final view: the coach, the controller, DraftService, the draft and the history with its two snapshots, all inside the Spring context.

Step 1 of 9

Undo from outside

The coach drafts the day's WOD: title, movements and time cap. If she makes a mistake and wipes the board, she wants to undo.

The first version opens every field of the draft with getters and setters, and it's ExposedDraftEditor that, before wiping, copies into its own variables what it thinks is needed.

Step 2 of 9

The field nobody copied

The editor copied the title and the movements… but not the time cap. Wiping leaves a blank board with the default cap, 20 minutes, and on undo "Fran" and its movements come back… with 20 minutes instead of 10. The ExposedDraftEditorTest test proves it.

And every new field of the draft is one more place to remember, outside the class that owns it.

Step 3 of 9

The snapshot, sealed

With Memento, the one copying the state is the draft itself. snapshot() creates a Snapshot with every field, and restore() puts them back.

Snapshot is a nested class with private fields and constructor: nobody outside WhiteboardDraft can create or read it. The list is copied with List.copyOf, so the snapshot doesn't change even if the draft keeps changing.

(One nuance: in Java privacy is per class, not per object, so any WhiteboardDraft could read another one's snapshot. Here there's a single draft; with several, the snapshot could store who created it and check it.)

Step 4 of 9

The history doesn't look inside

DraftHistory is the caretaker: it keeps snapshots on a stack and hands back the last one on undo. It never looks at what's inside, and it couldn't.

It has a maximum size (20 by default): when it's full, the oldest falls off. With no history, undo answers "nothing to undo". There's no redo here: that would take a second stack with the undone snapshots.

Step 5 of 9

When it saves

DraftService joins the two pieces. To edit, it first takes the snapshot, then edits, and only then saves it: if the edit isn't valid, the history doesn't change.

To undo, it asks the history for the last snapshot and hands it back to the draft with restore(). The service is synchronized because the draft and the history are state shared between requests. (An edit that changes nothing still saves a step; comparing first would avoid it, but here we keep it simple.)

Step 6 of 9

Everything comes back, the forgotten too

The test does the same as the earlier version: save, wipe the board and undo. This time the title, the movements and the 10-minute time cap come back. snapshot() could forget a field too, of course; what changes is that the slip would now sit next to the fields, in the same class, not scattered outside.

If tomorrow the draft gets a new field, it goes into Snapshot, snapshot() and restore(), all three inside the same class. The history never notices.

Step 7 of 9

Undo over HTTP

DELETE /api/draft wipes the board, leaving it blank with 20 minutes (and saves the snapshot first). POST /api/draft/undo brings it back: "Fran" returns with its 10 minutes.

An edit with a 0 time cap answers 400 and saves nothing; undo with no history answers 409 "nothing to undo".

Step 8 of 9

Spring already does it for you

Inside a transaction, TransactionStatus.createSavepoint() creates a savepoint: a marker of what your transaction had done up to that point (it doesn't undo what others commit). It's typed as Object, so your code isn't meant to look inside; you just hand it back to rollbackToSavepoint().

In the test, Ana logs 70 kg, the savepoint is created, someone types 700 by mistake and it goes back to the savepoint: one row is left, and the transaction is still alive. With a JDBC transaction manager, it's what Propagation.NESTED uses underneath.

Step 9 of 9

Recap

You started with an editor copying fields from outside and ended up with:

  • An originator, WhiteboardDraft, that takes and restores its own snapshots.
  • A memento, Snapshot, sealed: nobody else reads it.
  • A caretaker, DraftHistory, that keeps and hands back without looking.

Its neighbours: a Command undoes with an inverse operation (giving back the spot you booked); Memento fits when that inverse doesn't exist or is tricky, and a command often keeps a memento to be able to undo itself. Prototype copies an object too, but to create another one, not to go back. And an Iterator can use a memento to remember where it was.

When not to use it: if the state is huge and changes little, saving only the changes (or the inverse operation) is cheaper than copying it whole. And if the object is already immutable, you don't need Memento: keeping the reference is keeping the snapshot.

Cheatsheet →

Code

ExposedDraftEditor.java

public void clearBoard() {
    savedTitle = draft.getTitle();                       // the editor has to know every field…
    savedMovements = List.copyOf(draft.getMovements());
    draft.setTitle("Untitled");
    draft.setMovements(List.of());
    draft.setTimeCapMinutes(20);                         // …and the time cap was never saved
}

public void undo() {
    draft.setTitle(savedTitle);
    draft.setMovements(savedMovements);
}

ExposedDraftEditor.java

public void clearBoard() {
    savedTitle = draft.getTitle();                       // the editor has to know every field…
    savedMovements = List.copyOf(draft.getMovements());
    draft.setTitle("Untitled");
    draft.setMovements(List.of());
    draft.setTimeCapMinutes(20);                         // …and the time cap was never saved
}

public void undo() {
    draft.setTitle(savedTitle);
    draft.setMovements(savedMovements);
}

WhiteboardDraft.java

/** The memento: a frozen copy of the draft. Only WhiteboardDraft can read what's inside. */
public static final class Snapshot {
    private final String title;
    private final List<String> movements;
    private final int timeCapMinutes;

    private Snapshot(String title, List<String> movements, int timeCapMinutes) {
        this.title = title;
        this.movements = List.copyOf(movements);
        this.timeCapMinutes = timeCapMinutes;
    }
}

public Snapshot snapshot() {
    return new Snapshot(title, movements, timeCapMinutes);   // every field, without exposing any
}

public void restore(Snapshot s) {
    title = s.title;
    movements.clear();
    movements.addAll(s.movements);
    timeCapMinutes = s.timeCapMinutes;
}

DraftHistory.java

public void save(WhiteboardDraft.Snapshot snapshot) {
    snapshots.push(snapshot);
    if (snapshots.size() > size) snapshots.removeLast();   // the oldest falls off
}

public WhiteboardDraft.Snapshot undo() {
    if (snapshots.isEmpty()) throw new NothingToUndoException();
    return snapshots.pop();
}

DraftService.java

public synchronized DraftView edit(String title, List<String> movements, int cap) {
    WhiteboardDraft.Snapshot before = draft.snapshot();
    draft.edit(title, movements, cap);          // if this refuses, nothing is saved
    history.save(before);
    return view();
}

public synchronized DraftView clear() {
    history.save(draft.snapshot());
    draft.clear();
    return view();
}

public synchronized DraftView undo() {
    draft.restore(history.undo());
    return view();
}

WhiteboardDraftTest.java

WhiteboardDraft draft = new WhiteboardDraft("Fran", List.of("21-15-9 thrusters", "pull-ups"), 10);
DraftHistory history = new DraftHistory();

history.save(draft.snapshot());      // before the change
draft.clear();                       // oops: the whole board is gone
draft.restore(history.undo());

assertThat(draft.title()).isEqualTo("Fran");
assertThat(draft.timeCapMinutes()).isEqualTo(10);

DraftApiTest.java

mvc.perform(delete("/api/draft")).andExpect(jsonPath("$.movements").isEmpty());
mvc.perform(post("/api/draft/undo"))
   .andExpect(status().isOk())
   .andExpect(jsonPath("$.title").value("Fran"))
   .andExpect(jsonPath("$.timeCapMinutes").value(10));

SpringDoesItTooTest.java

jdbc.sql("insert into pr (athlete, lift, kg) values ('Ana', 'clean', 70)").update();
Object savepoint = status.createSavepoint();    // opaque: you can't look inside
jdbc.sql("insert into pr (athlete, lift, kg) values ('Ana', 'clean', 700)").update();   // typo
status.rollbackToSavepoint(savepoint);          // back to it; the transaction goes on

WhiteboardDraft.java

/** The memento: a frozen copy of the draft. Only WhiteboardDraft can read what's inside. */
public static final class Snapshot {
    private final String title;
    private final List<String> movements;
    private final int timeCapMinutes;

    private Snapshot(String title, List<String> movements, int timeCapMinutes) {
        this.title = title;
        this.movements = List.copyOf(movements);
        this.timeCapMinutes = timeCapMinutes;
    }
}

public Snapshot snapshot() {
    return new Snapshot(title, movements, timeCapMinutes);   // every field, without exposing any
}

public void restore(Snapshot s) {
    title = s.title;
    movements.clear();
    movements.addAll(s.movements);
    timeCapMinutes = s.timeCapMinutes;
}

Quiz

1. Who can read a Snapshot's fields?

2. You add a "scaling" field to the draft. What do you touch so undo brings it back?

3. Why does DraftService take the snapshot before editing but save it after?

4. How is a transaction savepoint like a Memento?

Cheatsheet →

Run it