AlgoViz

Ensuring proper encapsulation

medium 40 min

Private fields are the start, not the end.

Watch lesson4:46

View, snapshot, query

Three ways to let data out, with their cost and their surprises.

The point: a snapshot is safe and costs a copy. A view is free and moves under the reader. A query avoids the question.

See the difference

Python
from types import MappingProxyTypeclass Stock:    def __init__(self): self._n = {"pen": 5, "cup": 0}    def view(self): return MappingProxyType(self._n)   # live window    def snapshot(self): return dict(self._n)           # one moment    def in_stock(self, sku): return self._n.get(sku, 0) > 0    def sell(self, sku): self._n[sku] -= 1s = Stock()live, then = s.view(), s.snapshot()s.sell("pen")print("view", live["pen"], "| snapshot", then["pen"], "| query", s.in_stock("pen"))try:    live["pen"] = 99except TypeError as e:    print("view refuses:", e)try:    for sku in live: s._n["new"] = 1                   # owner adds while somebody loopsexcept RuntimeError as e:    print("loop broken:", e)
The view is safe for the owner. It is not safe for the reader, who sees changes in the middle of a loop.
Edit and run it in your browser

Which one?

SnapshotViewQuery methodStream or cursor
Cost per readn copiesconstantcost of the questionpage by page
Reader sees later changesnoyesanswer of that momentdepends
Inner objects safeonly if immutableonly if immutableyesif copied
Breaks while loopingnoyes, if owner writesno loopno
Representation stays hiddenmostlyless: callers use its typeyesyes

A budget, with numbers we assume: 10,000 references of 8 bytes are 80 KB per snapshot. At 500 reads a second that is 40 MB a second of short lived memory. A garbage collector may live with that, but it is worth a thought. At 20 elements nobody will ever measure it. Measure before you give up safety.

Cheap snapshots

  • Copy on write: keep an immutable tuple inside. Reads return it directly, writes build a new one. Java has CopyOnWriteArrayList; its documentation says copying is ordinarily too costly, but may be more efficient when traversals vastly outnumber mutations.
  • Cached snapshot: build the tuple at the first read, forget it on each write.
  • Persistent collections: share most of the structure between versions.
Python
class Board:    """Copy on write: reads are free, each write makes a new tuple."""    def __init__(self): self._rows = ()    def rows(self): return self._rows    def add(self, row): self._rows = (*self._rows, row)b = Board()b.add("a")first = b.rows()b.add("b")print(first, b.rows(), b.rows() is b.rows())
Edit and run it in your browser

Shallow is the usual bug

tuple(orders) protects the list of orders. Each order in it is still the real one. Three answers, best first: make the elements immutable; give out a small immutable summary of each; copy deeply. Deep copies can run into cycles and can copy far more than you think, so they are the last choice.

A dashboard reads 50,000 open orders every second. What does OrderBook return?

BreaksThe real list, with a comment
How
Fast. The comment says: do not change.
Limit
Someone sorts it for the screen, and matching breaks.
Choose when
Not across a class border.
WorksA full snapshot per read
How
tuple(orders) with frozen orders.
Limit
50,000 references, about 400 KB a second per reader. And most of it did not change.
Choose when
One reader, or a measurement says it is fine.
StrongAsk for what is shown
How
top(20) and total_open(), kept up to date on each write.
Limit
Each new question is a method or a small read model.
Choose when
Reads are frequent and narrow. Fall back to copy on write for the full list.