Making an Immutable Snapshot of a Record
An immutable snapshot preserves selected values at one moment so later mutations elsewhere cannot silently rewrite the observation.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Freeze the selected values
A record containing an identifier and a list of active tags can be represented by the identifier and a tuple of those tag strings. Later additions to the original list do not change the tuple. Tuple contents explain why this works for immutable strings.
Check deeper data
If each tag contains another mutable object, wrapping the list in a tuple alone still shares that object. Choose the snapshot depth required by its users or extract only primitive values. See shallow copying.[1]
Freeze every value that the reader can change
A report takes a snapshot of {"id": 12, "tags": ["draft"]}. Making a new mapping preserves its initial keys but can still share the list of tags. Updating the original list then changes the report. Store the tag values as an immutable sequence when the snapshot is supposed to remain historical. If the sequence contains mutable records, choose how to freeze their fields too. See shallow container copies.
Distinguish a snapshot from read-only access
A read-only view can prevent edits through one interface while reflecting ongoing changes through the owner. A dated snapshot should preserve the state actually observed at its capture point, with consistency across related fields if the data can change concurrently. Test both attempts to modify the returned result and later changes to its source. See dictionary views and snapshots.