On this page

Memento Pattern

Undo looks simple until you try to build it. To put an object back the way it was, something has to remember the way it was. The obvious way to do that is to let the undo code read every field and write them back later, but then the undo code knows the object's insides, every new field is a chance to forget one, and the object can no longer protect its own invariants. Memento solves the problem the other way round: the object packages its own state into a snapshot that nobody else can look inside, and takes it back when asked.

The grouped behavioral patterns overview doesn't cover Memento. This page does: the three roles, an editor with undo and redo in Java, Python and TypeScript, how each language keeps the snapshot opaque, what snapshots cost in memory, the shallow-copy bug that breaks most first attempts, and how Memento compares with Command-based undo.

Intent

Without violating encapsulation, capture an object's internal state in a separate object so that the original can be restored to that state later.

The phrase that matters is without violating encapsulation. Saving state is easy if you don't care who can see it. The pattern is about letting a third party (an undo stack, a checkpoint manager, a save-game slot) hold a snapshot without being able to read or change it.

The problem

Here's a first attempt at undo for a small text editor. The history class copies the editor's fields because they're public:

import java.util.ArrayDeque;
import java.util.Deque;

final class Editor {
    public String text = "";
    public int cursor = 0;
    public boolean bold = false;      // added later by another developer

    void type(String s) {
        text = text.substring(0, cursor) + s + text.substring(cursor);
        cursor += s.length();
    }
}

final class History {
    private record Saved(String text, int cursor) {}   // knows Editor's fields... most of them
    private final Deque<Saved> undo = new ArrayDeque<>();
    private final Editor editor;

    History(Editor editor) { this.editor = editor; }

    void checkpoint() { undo.push(new Saved(editor.text, editor.cursor)); }

    void undo() {
        Saved s = undo.pop();
        editor.text = s.text();
        editor.cursor = s.cursor();
        // bold was never saved, so it is never restored
    }
}

class BeforeDemo {
    public static void main(String[] args) {
        Editor editor = new Editor();
        History history = new History(editor);

        history.checkpoint();
        editor.type("hello");
        editor.bold = true;
        history.undo();

        assert editor.text.isEmpty() && editor.cursor == 0;
        assert editor.bold;                    // the bug: undo left bold switched on
        editor.cursor = 99;                    // and anyone can break the invariant
        System.out.println("before: ok (and buggy)");
    }
}

What's wrong:

  • The caretaker depends on the originator's internals. History lists Editor's fields. When someone adds bold, History silently stops being a full undo. Nothing fails to compile and no test fails unless someone thought to write one.
  • Encapsulation is gone. To make the fields copyable they had to be public, so any code can now set cursor = 99 on a 5-character document. The editor can't enforce "the cursor is between 0 and the text length" any more.
  • The restore logic is in the wrong class. Restoring might need more than assigning fields: re-validating, recomputing a cached word count, notifying listeners. Only Editor knows that, but History is the one doing the restoring.
  • It doesn't scale. With five kinds of undoable objects, you'd need five history classes that each know a different set of internals.

The fix is to turn it around: the editor produces a snapshot of all its state and knows how to apply one. The history just stores snapshots in order.

Structure

classDiagram
    class TextEditor {
        -text: String
        -cursor: int
        -bold: boolean
        +type(s: String) void
        +moveCursor(to: int) void
        +save() Snapshot
        +restore(s: Snapshot) void
    }
    class Snapshot {
        <<memento>>
        -text: String
        -cursor: int
        -bold: boolean
    }
    class History {
        -undo: Deque~Snapshot~
        -redo: Deque~Snapshot~
        -capacity: int
        +checkpoint() void
        +undo() boolean
        +redo() boolean
    }
    TextEditor ..> Snapshot : creates and reads
    History o-- Snapshot : stores, never reads
    History --> TextEditor : asks for save and restore

The undo flow, step by step:

sequenceDiagram
    participant U as User
    participant H as History
    participant E as TextEditor
    U->>H: checkpoint()
    H->>E: save()
    E-->>H: snapshot s1
    U->>E: type("hello")
    U->>H: undo()
    H->>E: save()
    E-->>H: snapshot s2, pushed on the redo stack
    H->>E: restore(s1)
    Note over H,E: History never looks inside s1 or s2

Participants

ParticipantRole in the exampleResponsibility
OriginatorTextEditorThe object whose state is saved. Creates a memento of its current state with save() and returns to a previous state with restore(). It's the only class that can read a memento's contents.
MementoSnapshotAn immutable value holding the originator's state at one moment. To everyone except the originator it's an opaque token: it can be stored and passed around, not inspected or changed.
CaretakerHistoryDecides when to take snapshots and which one to restore, and keeps them (a stack, a list of checkpoints, a save slot). Never reads or modifies their contents.

The design splits two kinds of knowledge cleanly. The originator knows what its state is. The caretaker knows when state should be captured and which past state the user wants back. Neither needs the other's knowledge.

Implementation

The editor below holds text, a cursor and a bold flag. It enforces the invariant that the cursor stays within the text. History supports undo and redo, clears the redo stack when a new change is made (otherwise "redo" would jump to a branch of history that no longer makes sense), and keeps at most capacity undo steps so memory stays bounded.

import java.util.ArrayDeque;
import java.util.Deque;

final class TextEditor {
    private String text = "";
    private int cursor = 0;
    private boolean bold = false;

    /** The memento. Its fields and constructor are private, so only TextEditor can create or read it. */
    static final class Snapshot {
        private final String text;
        private final int cursor;
        private final boolean bold;

        private Snapshot(String text, int cursor, boolean bold) {
            this.text = text;
            this.cursor = cursor;
            this.bold = bold;
        }
    }

    void type(String s) {
        text = text.substring(0, cursor) + s + text.substring(cursor);
        cursor += s.length();
    }

    void moveCursor(int to) {
        if (to < 0 || to > text.length()) throw new IllegalArgumentException("cursor out of range: " + to);
        cursor = to;
    }

    void toggleBold() { bold = !bold; }

    Snapshot save() { return new Snapshot(text, cursor, bold); }   // String is immutable, so no copy needed

    void restore(Snapshot s) {
        text = s.text;
        cursor = s.cursor;
        bold = s.bold;
    }

    String text() { return text; }
    int cursor() { return cursor; }
    boolean bold() { return bold; }
}

final class History {
    private final TextEditor editor;
    private final int capacity;
    private final Deque<TextEditor.Snapshot> undo = new ArrayDeque<>();
    private final Deque<TextEditor.Snapshot> redo = new ArrayDeque<>();

    History(TextEditor editor, int capacity) {
        this.editor = editor;
        this.capacity = capacity;
    }

    /** Call before every change the user should be able to undo. */
    void checkpoint() {
        undo.push(editor.save());
        if (undo.size() > capacity) undo.removeLast();   // forget the oldest step
        redo.clear();                                      // a new change ends the redo branch
    }

    boolean undo() {
        if (undo.isEmpty()) return false;
        redo.push(editor.save());
        editor.restore(undo.pop());
        return true;
    }

    boolean redo() {
        if (redo.isEmpty()) return false;
        undo.push(editor.save());
        editor.restore(redo.pop());
        return true;
    }
}

class EditorDemo {
    public static void main(String[] args) {
        TextEditor editor = new TextEditor();
        History history = new History(editor, 2);

        history.checkpoint(); editor.type("hello");
        history.checkpoint(); editor.toggleBold();
        history.checkpoint(); editor.type(" world");
        assert editor.text().equals("hello world") && editor.bold();

        assert history.undo();
        assert editor.text().equals("hello") && editor.bold() && editor.cursor() == 5;
        assert history.undo();
        assert editor.text().equals("hello") && !editor.bold();
        assert !history.undo();                       // capacity 2: the first step was forgotten

        assert history.redo() && editor.bold();
        history.checkpoint(); editor.type("!");       // new change clears redo
        assert !history.redo();
        assert editor.text().equals("hello!");
        System.out.println("editor history: ok");
    }
}
from __future__ import annotations

from collections import deque
from dataclasses import dataclass


@dataclass(frozen=True)
class Snapshot:
    """The memento. Frozen, so a caretaker can't change it. By convention only TextEditor reads it."""
    _text: str
    _cursor: int
    _bold: bool


class TextEditor:
    def __init__(self) -> None:
        self._text = ""
        self._cursor = 0
        self._bold = False

    def type(self, s: str) -> None:
        self._text = self._text[: self._cursor] + s + self._text[self._cursor :]
        self._cursor += len(s)

    def move_cursor(self, to: int) -> None:
        if not 0 <= to <= len(self._text):
            raise ValueError(f"cursor out of range: {to}")
        self._cursor = to

    def toggle_bold(self) -> None:
        self._bold = not self._bold

    def save(self) -> Snapshot:
        return Snapshot(self._text, self._cursor, self._bold)  # str is immutable, no copy needed

    def restore(self, s: Snapshot) -> None:
        self._text, self._cursor, self._bold = s._text, s._cursor, s._bold

    @property
    def text(self) -> str:
        return self._text

    @property
    def cursor(self) -> int:
        return self._cursor

    @property
    def bold(self) -> bool:
        return self._bold


class History:
    def __init__(self, editor: TextEditor, capacity: int) -> None:
        self._editor = editor
        self._undo: deque[Snapshot] = deque(maxlen=capacity)  # oldest step drops off automatically
        self._redo: list[Snapshot] = []

    def checkpoint(self) -> None:
        """Call before every change the user should be able to undo."""
        self._undo.append(self._editor.save())
        self._redo.clear()  # a new change ends the redo branch

    def undo(self) -> bool:
        if not self._undo:
            return False
        self._redo.append(self._editor.save())
        self._editor.restore(self._undo.pop())
        return True

    def redo(self) -> bool:
        if not self._redo:
            return False
        self._undo.append(self._editor.save())
        self._editor.restore(self._redo.pop())
        return True


if __name__ == "__main__":
    editor = TextEditor()
    history = History(editor, capacity=2)

    history.checkpoint(); editor.type("hello")
    history.checkpoint(); editor.toggle_bold()
    history.checkpoint(); editor.type(" world")
    assert editor.text == "hello world" and editor.bold

    assert history.undo()
    assert editor.text == "hello" and editor.bold and editor.cursor == 5
    assert history.undo()
    assert editor.text == "hello" and not editor.bold
    assert not history.undo()  # capacity 2: the first step was forgotten

    assert history.redo() and editor.bold
    history.checkpoint(); editor.type("!")  # new change clears redo
    assert not history.redo()
    assert editor.text == "hello!"
    print("editor history: ok")
/** The memento as seen from outside: an opaque, frozen token with no readable state. */
interface Snapshot {
  readonly takenAt: number;
}

interface EditorState {
  readonly text: string;
  readonly cursor: number;
  readonly bold: boolean;
}

class TextEditor {
  private text = "";
  private cursor = 0;
  private bold = false;
  private counter = 0;
  // Only the editor can map a token back to its state. Tokens from another editor won't resolve.
  private readonly states = new WeakMap<Snapshot, EditorState>();

  type(s: string): void {
    this.text = this.text.slice(0, this.cursor) + s + this.text.slice(this.cursor);
    this.cursor += s.length;
  }

  moveCursor(to: number): void {
    if (to < 0 || to > this.text.length) throw new RangeError(`cursor out of range: ${to}`);
    this.cursor = to;
  }

  toggleBold(): void {
    this.bold = !this.bold;
  }

  save(): Snapshot {
    const token: Snapshot = Object.freeze({ takenAt: ++this.counter });
    this.states.set(token, { text: this.text, cursor: this.cursor, bold: this.bold });
    return token;
  }

  restore(token: Snapshot): void {
    const state = this.states.get(token);
    if (state === undefined) throw new Error("snapshot does not belong to this editor");
    ({ text: this.text, cursor: this.cursor, bold: this.bold } = state);
  }

  get view(): EditorState {
    return { text: this.text, cursor: this.cursor, bold: this.bold };
  }
}

class EditHistory {
  private readonly undoStack: Snapshot[] = [];
  private readonly redoStack: Snapshot[] = [];

  constructor(private readonly editor: TextEditor, private readonly capacity: number) {}

  /** Call before every change the user should be able to undo. */
  checkpoint(): void {
    this.undoStack.push(this.editor.save());
    if (this.undoStack.length > this.capacity) this.undoStack.shift(); // forget the oldest step
    this.redoStack.length = 0; // a new change ends the redo branch
  }

  undo(): boolean {
    const previous = this.undoStack.pop();
    if (previous === undefined) return false;
    this.redoStack.push(this.editor.save());
    this.editor.restore(previous);
    return true;
  }

  redo(): boolean {
    const next = this.redoStack.pop();
    if (next === undefined) return false;
    this.undoStack.push(this.editor.save());
    this.editor.restore(next);
    return true;
  }
}

function check(condition: boolean, message: string): void {
  if (!condition) throw new Error(`check failed: ${message}`);
}

const editor = new TextEditor();
const edits = new EditHistory(editor, 2);

edits.checkpoint(); editor.type("hello");
edits.checkpoint(); editor.toggleBold();
edits.checkpoint(); editor.type(" world");
check(editor.view.text === "hello world" && editor.view.bold, "edits applied");

check(edits.undo(), "undo 1");
check(editor.view.text === "hello" && editor.view.bold && editor.view.cursor === 5, "after undo 1");
check(edits.undo(), "undo 2");
check(editor.view.text === "hello" && !editor.view.bold, "after undo 2");
check(!edits.undo(), "capacity 2: the first step was forgotten");

check(edits.redo() && editor.view.bold, "redo");
edits.checkpoint(); editor.type("!");
check(!edits.redo(), "new change clears redo");
check(editor.view.text === "hello!", "final text");

let foreignRejected = false;
try {
  new TextEditor().restore(editor.save());
} catch {
  foreignRejected = true;
}
check(foreignRejected, "snapshots are tied to their editor");
console.log("editor history: ok");

Points worth calling out in an interview:

  • save() captures everything, so adding a field is a one-class change. When bold was added, only TextEditor (its field, save and restore) changed. History didn't, and couldn't have forgotten anything, because it never knew the fields in the first place.
  • The invariant is safe. Fields are private again. The only way to set cursor from outside is moveCursor, which checks the range. restore can set fields directly because a snapshot can only have come from a valid editor state.
  • Undo saves the current state onto the redo stack before restoring. That's what makes redo possible. Forgetting it is the most common bug in hand-written undo.
  • A new change clears redo. If you undo twice and then type, the two undone steps are no longer reachable. Editors that keep them (an "undo tree", as Vim does) are a deliberate extension, not the default.
  • History is bounded. Unbounded undo stacks are a memory leak that grows with the user's session. Java removes the oldest entry by hand, Python's deque(maxlen=...) does it automatically, and TypeScript uses shift(), which is O(n) but fine for a capacity of a few hundred. Swap in a ring buffer if the capacity is large.

Keeping the memento opaque

"Only the originator can read the memento" is easy to say and enforced differently in each language:

LanguageTechnique used aboveWhat it guarantees
JavaMemento is a static nested class of the originator with private fields and a private constructor. The outer class can access a nested class's private members; nobody else can.Enforced by the compiler. Outside code can hold a TextEditor.Snapshot but can't create one or read it.
PythonA frozen dataclass whose fields start with _.Convention plus immutability. A caretaker could read _text, but linters flag it and it can't modify the snapshot. Python doesn't offer stronger privacy, and the community accepts that trade-off.
TypeScriptThe public Snapshot type has no state, only a token. The real state lives in a WeakMap inside the editor, keyed by the token.Enforced at runtime, not just by types. It also rejects snapshots from a different editor instance, and the WeakMap lets a state be garbage-collected once nobody holds its token.

Other options you might mention: C++ uses friend to give the originator exclusive access; Kotlin can use an internal or private nested class; some designs expose a narrow interface (interface Memento { String label(); }) to the caretaker and a wide one to the originator.

The stricter you make it, the more ceremony you add. For a small in-process editor, a well-named immutable value is often enough. For a library whose users write the caretaker, compiler-enforced opacity is worth the extra lines.

What a snapshot costs

A memento is a copy of state. How expensive that copy is depends on the state's shape.

  • Immutable values are free to share. Java Strings, Python strs and tuples, and TypeScript strings can't change, so the snapshot can hold the same object the editor holds. Saving a 1 MB document costs a reference, not a megabyte, until the editor replaces the text with a new string.
  • Mutable collections must be copied. If the originator holds a list, map or array, the memento must copy it, or the "snapshot" changes whenever the original does. For nested structures, the copy must go as deep as the mutability does.
  • Large state calls for a different design. Snapshotting a 50 MB image after every brush stroke would exhaust memory quickly. Options: store only the changed region (a delta), store the operation instead of the state (that's Command-based undo, below), or snapshot every N operations and replay the operations in between.
  • Persistent data structures change the maths. Immutable collections with structural sharing (Clojure's vectors, Immutable.js, the immutable state style of Redux) make every past version available at the cost of the parts that changed. With them, a memento is just the old root reference. This is why time-travel debugging is easy in Redux: every past state still exists, unchanged.

The shallow-copy bug

The most common Memento bug in practice: the snapshot copies the outer object but shares a mutable inner one. Restoring then brings back the current inner state, not the saved one.

from __future__ import annotations

import copy
from dataclasses import dataclass


class Board:
    """A small game board: a grid of cells plus a score."""

    def __init__(self) -> None:
        self.cells: list[list[str]] = [["." for _ in range(3)] for _ in range(3)]
        self.score = 0

    def place(self, row: int, col: int, mark: str) -> None:
        self.cells[row][col] = mark
        self.score += 1

    def save_shallow(self) -> BoardSnapshot:
        return BoardSnapshot(self.cells, self.score)                 # BUG: shares the inner lists

    def save_shallow_copy(self) -> BoardSnapshot:
        return BoardSnapshot(list(self.cells), self.score)           # STILL A BUG: rows are shared

    def save(self) -> BoardSnapshot:
        return BoardSnapshot(tuple(tuple(r) for r in self.cells), self.score)  # immutable copy

    def restore(self, s: BoardSnapshot) -> None:
        self.cells = [list(r) for r in s.cells]                      # fresh mutable lists again
        self.score = s.score


@dataclass(frozen=True)
class BoardSnapshot:
    cells: object
    score: int


if __name__ == "__main__":
    for saver in ("save_shallow", "save_shallow_copy"):
        board = Board()
        snap = getattr(board, saver)()
        board.place(1, 1, "X")
        board.restore(snap)
        assert board.score == 0          # the int was copied correctly...
        assert board.cells[1][1] == "X"  # ...but the move survived the "undo"

    board = Board()
    snap = board.save()
    board.place(1, 1, "X")
    board.restore(snap)
    assert board.cells[1][1] == "." and board.score == 0

    # copy.deepcopy also works, but copying into immutable tuples makes the memento safe to share.
    deep = copy.deepcopy(board.cells)
    board.place(0, 0, "O")
    assert deep[0][0] == "."
    print("shallow-copy bug: ok")

Note that frozen=True on the snapshot didn't help the buggy versions. Freezing the dataclass stops you reassigning snap.cells; it doesn't stop the list inside it from changing. Converting to tuples makes the snapshot immutable all the way down, and restore converts back to fresh lists so the editor and the snapshot never share anything mutable. In Java, the same trap appears when a snapshot holds a reference to an ArrayList or an array. Use List.copyOf (which creates an unmodifiable copy) or clone the array.

Memento vs Command for undo

There are two ways to implement undo, and interviewers like to ask which you'd pick.

Memento (snapshot) undoCommand (operation) undo
What's storedThe whole state before each changeEach operation plus enough data to reverse it
Undo meansRestore the previous snapshotRun the operation's inverse
Writing itEasy and uniform: one save/restore pair covers every operationEach command needs a correct undo(), and a wrong one corrupts state
MemoryProportional to state size per step, so large states get expensiveProportional to the size of each change, usually small
Correctness riskLow, as long as the snapshot copies deeply enoughInverse operations can drift from forward ones as code changes
Good fitSmall or immutable state, forms, game positions, configurationLarge documents, drawings, anything where a step changes a small part of a big state

They combine well. A common hybrid is a command that captures a memento of just the part it changes before executing and restores it on undo. You get commands' small memory footprint without hand-writing an inverse for every operation. The chess case study takes the command route for move undo, because a move changes two squares of a 64-square board and its inverse is simple. At larger scale, event-sourced systems use the same split: they replay events (commands) for history and take periodic state snapshots (mementos) so they don't have to replay from the beginning. See snapshots in event sourcing.

Persisting snapshots

Mementos don't have to live in memory. A save-game slot, a draft that survives a browser refresh, or a checkpoint in a long batch job are all mementos written to disk. Once a snapshot outlives the process, three new concerns arrive:

  1. Versioning. The snapshot format will change as the originator gains fields. Write a version number into every persisted snapshot, and have the originator know how to read older versions (or refuse them clearly).
  2. Integrity. A file can be truncated or edited. Validate on restore: check the version, required fields and invariants (a cursor within the text, a score that isn't negative) before you apply anything.
  3. Opacity still matters. Keep the serialisation code in the originator. If the save-game manager starts parsing the snapshot, you're back to the caretaker knowing the internals.

Real-world uses

  • Undo in editors and design tools. Most editors use some mix of snapshot and command undo. The snapshot side is Memento.
  • Android's saved instance state. An activity writes its UI state into a Bundle in onSaveInstanceState. The system holds the bundle (the caretaker) and hands it back when it recreates the activity, for example after a configuration change. The activity alone decides what goes in and how to read it back.
  • The browser History API. history.pushState(state, ...) associates a state object with a history entry, and the popstate event hands that state back when the user navigates to the entry. The browser stores the snapshot. The page decides what it means.
  • Redux DevTools time travel. Because Redux state is treated as immutable, every past state can be kept cheaply, and the DevTools let you jump back to any of them. Each stored state is effectively a memento of the whole app.
  • Game saves and checkpoints. The game serialises its world state to a slot and restores it later. Slot management (the caretaker) knows nothing about what's inside.
  • Database savepoints, as an analogy. SAVEPOINT and ROLLBACK TO SAVEPOINT let a transaction return to an earlier point. Databases implement this with logs rather than copies of the data, but the interface (mark a point, return to it later, without knowing how) is the same idea.

When NOT to use it

  • The state is large and changes in small steps. Full snapshots of a big document or image after every keystroke waste memory. Use command-based undo, deltas or periodic snapshots.
  • The state isn't all in the object. If restoring the editor should also undo a file write, a network call or an email, a snapshot can't do it. External side effects need compensating actions (Command, or a saga at system level), not mementos.
  • Encapsulation doesn't matter here. For a plain data record with public fields, such as a DTO or a configuration value, just copy it. Wrapping it in a memento adds ceremony for nothing.
  • The state is already immutable. If every change produces a new value (a Redux reducer, a functional core), keeping the old value is the snapshot. A separate memento class only adds indirection.
  • Snapshots would hold resources. A memento that captures an open file handle, a socket or a lock is a bug waiting to happen. Snapshot the data, not the resources.
PatternHow it differs
CommandStores operations rather than state. The two are the main ways to implement undo and are often combined: a command keeps a memento of what it changes.
PrototypeAlso copies an object. Prototype creates a new, independent, usable object from an existing one. A memento is an opaque record used only to restore the original. Prototype's clone can sometimes be the memento for simple objects.
IteratorAn iterator's position can be captured as a memento so a traversal can be paused and resumed.
StateState changes behaviour by switching state objects. Memento saves and restores data. A state machine can be checkpointed with a memento that records the current state and its data.
ObserverAfter restore(), listeners usually need to hear about the new state. The originator should notify them from inside restore, since only it knows what changed.

The smell that suggests it

  • An undo or "reset" feature that reads and writes another object's fields, especially if those fields were made public to allow it.
  • "Revert" bugs after a new field is added: undo works for everything except the new thing, because the save code lists fields by hand.
  • Copy-paste of state into local variables before a risky operation ("save these five fields, try the operation, put them back if it fails") repeated in several places.
  • Getters and setters that exist only so another class can back up and restore state.
  • A requirement for checkpoints, drafts, save slots or time travel in the problem statement.

Interview questions

  1. "How would you implement undo and redo for a text editor?" Two stacks. Before each change, push a snapshot onto the undo stack and clear the redo stack. On undo, push the current snapshot onto redo and restore the top of undo. On redo, the reverse. Bound the undo stack. Then mention the alternative (command-based undo) and when you'd switch to it: large documents where snapshots get expensive.
  2. "Why not just make the fields public and copy them?" Because then the history class depends on every field, forgets new ones silently, and the originator can no longer enforce its invariants. Memento keeps the knowledge of what to save in the object that owns the state.
  3. "Memento or Command for undo?" Memento when state is small or immutable and you want uniform, low-risk undo. Command when state is large and changes are small, or when operations already exist as objects. Often both: commands that capture a memento of the part they change.
  4. "How do you keep the memento opaque in Java? In Python?" Java: a nested class with private fields and constructor, which only the enclosing class can access. Python: a frozen dataclass with underscore-prefixed fields; privacy is by convention, immutability is enforced. TypeScript: a token type with the real state held in a WeakMap inside the originator.
  5. "Your undo restores the score but not the board. Why?" A shallow copy: the snapshot shared the mutable grid with the live object, so later moves changed the snapshot too. Copy deeply enough, ideally into immutable structures, and have restore build fresh mutable copies.
  6. "How do you stop the undo history using too much memory?" Cap the number of steps (a bounded deque or ring buffer), share immutable data between snapshots, store deltas instead of full states, or snapshot every N operations and replay commands in between.
  7. "What if restoring must also undo a payment or an email?" A memento can't. It only covers in-memory state. External effects need explicit compensating operations (a refund, a correction email), designed as commands or as a saga in a distributed system.
  8. "How would you persist snapshots, such as save games?" Serialise inside the originator, include a format version, validate invariants when loading, and keep the slot manager ignorant of the contents. Plan for reading older versions from day one.

Further reading