Pragmatic Objects
  • Pragmatic Objects
  • What's an Object ?
  • Thinking Object
  • Practices
    • The Pragmatic Practices
    • No Getters & Setters
    • Inherit Wisely
    • Wrap Null
    • Wrap Primitives
    • Wrap Collections
    • Expose Snapshots
    • Abandon Composed Names
    • Don't Check Types
    • Minimize Knowledge
    • Immutability
    • Separate Commands & Queries
    • Abandon Statics
    • Invert Dependencies
  • Patterns
    • Domain Model
    • Always Valid
    • Wrapper
    • Command
    • Procedural Object
    • Compute Object
    • Snapshot
    • Value Object
    • Observability
  • Examples
    • Celsiuses / Fahrenheits
Powered by GitBook
On this page
  1. Patterns

Snapshot

Represent the public state of an object at a point in time

Temporality is often considered important when talking Snapshot.

In our case, it's a side effect. The most important property of a Snapshot is that it's a value representing what an object is willing to expose, in order to be saved into a database or to be serialized for public access.

Our snapshot system needs two methods

  • A snapshot method : to create a snapshot of the specific object

  • A fromSnapshot static factory : to create an object from the snapshot

The following property must be true.

Object.fromSnapshot(obj.snapshot()) == obj

Snapshot often follows a composite structure : nested objects also need to be snapshotted, so they must also implement a Snapshottable interface.

type State = {
  id: string;
  creditPoints: number;
  schedule: Schedule;
};

type Snapshot = {
  id: string;
  creditPoints: number;
  schedule: GetSnapshot<Schedule>;
};

export class Student extends Entity<State, Snapshot> {
  static fromSnapshot(snapshot: Snapshot): Student {
    return new Student({
      id: snapshot.id,
      creditPoints: snapshot.creditPoints,
      schedule: Schedule.fromSnapshot(snapshot)
    })
  }

  snapshot(): Snapshot {
    return {
      id: this._state.id,
      creditPoints: this._state.creditPoints,
      schedule: this._state.schedule.snapshot(),
    };
  }
}
PreviousCompute ObjectNextValue Object

Last updated 1 year ago