Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Memento

Intent

Capture an object’s state as a sealed snapshot so it can be restored later without exposing its internals.

Motivation

A text editor types freely but must undo back to an earlier draft. Letting the undo stack poke at the editor’s buffers couples history to editing guts. A snapshot object that the editor fills and later replays lets history store opaque drafts while only the editor reads them.

Structure

flowchart LR
  Editor[Editor Originator] --> Snap[Snapshot Memento]
  Keeper[History Caretaker] --> Snap
  Editor --> Keeper
  • Originator (Editor) — creates snapshots of itself and restores from them; the only one that reads snapshot contents.
  • Memento (Snapshot) — an opaque saved state; exposes nothing to outsiders.
  • Caretaker (History) — stores and returns snapshots without inspecting them.

Consequences

  • Benefit: undo works without breaking encapsulation; the caretaker never learns the originator’s internals.
  • Cost: snapshots consume memory — cap history depth or store deltas for large states.

Basic Recap

Memento captures an object’s state so it can be restored later without exposing the object’s internal representation to caretakers. The originator creates and interprets its snapshots, while a caretaker stores and retrieves them. This preserves encapsulation and supports features such as undo or checkpointing. A memento records internal state, not every external effect the originator may have caused since the snapshot.

Complex Scenario

A visual infrastructure editor lets engineers rearrange a deployment graph, edit node settings, and undo several changes before publishing. The graph originator creates versioned mementos containing its internal layout and configuration, and the history caretaker retains a bounded stack. Publishing to cloud infrastructure remains a separate operation. Restoring a draft therefore changes only the editor model and never claims to undeploy resources.

Edge cases

  • Memory pressure: Full deep snapshots of a large graph can exhaust memory; structural sharing or deltas can help, but history must remain immutable and size limits must be explicit.
  • Concurrency: Restoring an old memento while another user has saved a newer draft requires a version check or merge decision, not silent last-writer-wins.
  • Partial failure: Deserialization may fail midway because a plugin is missing; restore should validate into a temporary model and swap only after the complete snapshot is usable.

The memento format needs schema versioning and secret handling if snapshots leave process memory or survive application upgrades.

Sketch (illustrative pseudocode, not runnable):

GraphEditor.capture():
    return Memento(
        schemaVersion = CURRENT,
        baseVersion = this.version,
        state = immutableCopy(this.internalGraph)
    )

History.restore(snapshot):
    candidate = GraphEditor.fromValidatedSnapshot(snapshot)
    if snapshot.baseVersion != currentSavedVersion:
        return Conflict(requiresMerge = true)
    editor.replaceModelAtomically(candidate)
    editor.notifyDraftChanged()  # no infrastructure deployment

When to Use / When Not to Use

Use when:

  • Users need undo, rollback, or checkpoints over state you want to keep private.
  • Snapshot/restore must not couple history code to internal fields.

Avoid when:

  • State is huge and copied often, or callers legitimately need structured access — prefer explicit save/load or commands storing deltas.

Examples

  • examples/elixir/memento/
  • examples/dart/memento/
  • examples/go/memento/
  • examples/rust/memento/

Expected outcome: typing extends the draft, a snapshot is kept, and restore prints the earlier text.

Anti-pattern / Failure Mode

  • Misuse: Snapshots taken so often that memory grows without a restore need.

  • Review signal: Mementos exposing internals they were meant to encapsulate.

  • Misuse symptom: Caretakers read and modify memento fields, turning the snapshot into a public duplicate of the model. Capturing database sessions, listeners, credentials, or entire service graphs makes restore unsafe and breaks the boundary the pattern is meant to protect.

  • Review signal: Look for mementos serialized without version or sensitivity policy, unbounded undo stacks, and restore methods that mutate the live model before validation completes. Claims that undo reverses emails, payments, or deployments are a product-level warning that internal snapshots are being confused with external compensation.

Exercise

Keep two snapshots and add undo-twice support. Then cap history at depth 1 and document which restore now fails and why.

Self-check

  • Who may read a snapshot’s contents?
    AnswerOnly the originator that made it — the caretaker stores and returns it blindly.
  • Memento vs Command for undo: what differs?
    AnswerMemento restores saved state snapshots; Command replays inverse actions. Snapshots are simpler but heavier.
  • What bounds memory use?
    AnswerHistory depth caps, delta snapshots, or discarding redo branches on new edits.