Memento
Purpose
Let something outside an object hold that object's past state without being able to read or corrupt it. The caretaker keeps the capture and hands it back; only the originator understands what is inside.
That opacity is the pattern, and it is what a getState()/setState() pair is not: exposing the
state as a public structure lets any holder inspect it, mutate it, and depend on its shape, which
is the coupling the pattern exists to prevent.
Inspect the project's compiler release/toolchain and state ownership before changing the API. Examples are partial Java 17 snippets (records and sealed types, no preview); imports, domain types and mutators are omitted. Keep the project baseline rather than upgrading it for a pattern.
Memento, snapshot, event sourcing
Memento opaque to its caretaker; restores an originator to prior
state. It may be transient or durable—the pattern does not
remove schema/versioning duties when persisted.
Answers: what was it?
Snapshot a state capture, often durable/serialized and consumed across
versions, so it needs a schema and compatibility policy.
Answers: what was it, later and elsewhere?
Event sourcing state is derived by replaying an append-only log of
facts. Snapshots become an optimisation over replay.
Answers: what was it, AND why did it become that?
Choose by recovery and history requirements. Audit value alone does not require event sourcing:
a separate audit trail may suffice. Event sourcing makes the event log authoritative and pays for
replay and schema evolution; snapshots alone cannot reconstruct unrecorded intervening changes
(event-sourcing).
A durable state document can be both a snapshot and the memento in an undo/recovery design. The important review point is not the label: persistence and cross-version readers make its schema a contract regardless of pattern name.
When it is the answer
Undo or revert of in-memory work, where the operation's inverse is
hard to compute or lossy
→ Memento. Cheaper to remember the old value than to invert.
A what-if branch: the user explores a change and may discard it
→ Memento of the pre-state, or a copy of the working object.
A long computation must be resumable after a failure
→ a checkpoint/durable snapshot; it may play the memento role,
but needs consistency, format and version policy.
When it is not
- The object is immutable. It is already its own memento: keep the reference. This removes
most proposed uses (
java-immutability). - The operation has a cheap exact inverse.
Move(+5)can undo withMove(-5)only without rounding, clamping, overflow or conflicting intervening edits (gof-command). - The capture must survive the process. Memento alone is insufficient guidance: add durable snapshot consistency, schema, compatibility, corruption and recovery semantics.
- State must be rebuilt from authoritative changes. Route event sourcing decisions to
event-sourcing; audit-only requirements may use a separate history. - The "memento" is passed to another module that reads it. Then it is a DTO with a contract, and the encapsulation the pattern promised is gone.
Modern Java expression
Classical Modern
───────────────────────────────── ────────────────────────────────────
class Memento with package- a private nested record inside the
private accessors originator — opaque by construction
originator.setMemento(m) originator.restore(m), where the
parameter type is a public marker
interface the caretaker cannot read
deep-copied mutable state immutable components; capture is then
a field copy with no defensive copying
full state per undo step the object is immutable and the "undo
stack" is a stack of references, with
structural sharing between versions
public final class Editor {
public sealed interface Snapshot permits State { } // opaque to callers
private final Object owner = new Object();
private record State(Object owner, String text, int caret, List<Mark> marks) implements Snapshot {
@Override public String toString() { return "Editor snapshot"; }
}
public Snapshot capture() { return new State(owner, text, caret, List.copyOf(marks)); }
public void restore(Snapshot snapshot) {
if (!(snapshot instanceof State state) || state.owner() != owner) {
throw new IllegalArgumentException("foreign or null snapshot");
}
this.text = state.text();
this.caret = state.caret();
this.marks = new ArrayList<>(state.marks());
}
}
A private implementation hides typed accessors from ordinary callers. Generated record
toString() exposes components unless overridden; equality/hash codes also remain observable.
This is API encapsulation, not a security boundary against reflection. The example rejects
captures from another Editor and assumes immutable Mark values plus thread confinement.
List.copyOf copies the list structure, not mutable elements.
Decision rules
IF the originator is immutable
THEN there is no memento to design. Keep the old reference.
IF the caretaker reads fields of the capture
THEN encapsulation is broken and the capture is now a contract. Either
narrow the type, or accept it is a DTO and version it.
IF the capture shares mutable structure with the originator
THEN restoring later restores whatever it has become, not what it was.
Copy the mutable parts at capture time.
IF the source can be mutated while it is being captured
THEN the capture may hold fields from two different states. Capture
under the same lock as the mutators, or from an immutable value.
IF an undo stack holds full captures of a large object
THEN memory is depth × size. Prefer command inverses, diffs, or
persistent structures with structural sharing.
IF the capture is written to storage or sent to another process
THEN it is also a wire/storage snapshot: it needs a stable format and explicit
compatibility strategy. A literal version field is one mechanism, not mandatory
when schema identifiers/envelopes or evolution rules provide the version.
IF restoring must also restore things outside the object — files sent,
messages published, money moved
THEN restore is not enough; that is compensation
(distributed-transactions-and-sagas).
IF what changed matters as much as what it was
THEN consider event sourcing before building a snapshot history that
will never answer "why".
Cross-cutting checks
- Concurrency. Capturing is a multi-field read and is not atomic: a concurrent mutation
produces a capture the object never had. The same applies to
restore, which must not be observable half-applied. Either both run under the lock that guards the state, or the state is an immutable state value swapped through a singlevolatile/atomic reference—in which case capture/restore of that state reference is atomic, provided no related state lives outside it (java-memory-model). - Distribution. A persisted memento is also a serialized snapshot with a schema identity
and evolution policy. Reject unsupported meaning rather than assuming tolerant reading is safe;
added fields need validated defaults or a migration. Distributed checkpointing across processes
is a different problem requiring barriers or a consistent-cut algorithm
(
distributed-aggregation-and-barriers). - Performance. A full-copy upper bound is depth × state size, but structural sharing, deduplication
and variable diffs change retained size; measure the reachable graph.
Options in order of preference — make the object immutable and share structure between versions;
store inverses instead of states; store diffs; bound the depth. Also watch retention: an undo
stack holding large graphs keeps them alive and is a common source of "the heap grows during a
long editing session" (
heap-dump-analysis). - Testing. The property to assert is a round trip:
restore(capture(s))leaves the object equal tos, over generated states, plus mutate-after-capture and restore-after-intervening-change cases. It catches omitted state only when generators and semantic equality include that state.
Review checklist
Return the capture boundary and ownership, concurrency/restore-conflict policy, memory bound, and checks executed versus pending. Missing state or deployment evidence leaves completeness and compatibility conditional; enumerate fields and external effects before proposing restore.
- The originator is genuinely mutable; otherwise the capture is a reference
- The capture type is opaque to the caretaker
- Every mutable component is copied at capture time
- Capture and restore are atomic with respect to concurrent mutation
- Independent semantic observations cover every restorable field; capture equality alone is insufficient
- Undo depth is bounded, and the memory cost was calculated
- A durable capture has an explicit schema identity/evolution strategy and corruption handling
- External effects are compensated, not "restored"
- Persisted captures are treated as snapshots/contracts even when they also serve as mementos
References
- Memento, snapshot and event sourcing — the three compared on durability, schema, history and cost; Java encapsulation techniques for an opaque capture; memory strategies for undo stacks (inverses, diffs, persistent structures); and versioning rules once a capture becomes durable. Read when choosing between them.
- Worked example — a multi-step form with undo built on an opaque memento, converted to an immutable state with structural sharing when the stack grew, plus a batch job checkpoint that deliberately is a versioned snapshot rather than a memento. Read when implementing.