AlgoViz

Ensuring proper encapsulation

medium 40 min

Private fields are the start, not the end.

Watch lesson4:46

Remember it

The few things worth knowing cold, and how to make them stick.

Memory hook

Seal the farm: one hatch, it checks, photos go out, strings are cut.

A glass ant farm with one feeding hatch. Stones are refused, photos of the queen go out, strings on leaves are cut, and the side panel is screwed on.

Cheat sheet

In
copy, check the copy, store
Out
value, snapshot, view, or an answer
Change
check, compute, write
Two linked fields
one method
Java snapshot / view
`List.copyOf` / `unmodifiableList`
Python
`tuple`, `frozenset`, `MappingProxyType`
TypeScript
`#field`, `readonly T[]`, spread
C++
by value or `const&`
Callbacks
last, over a copied list
Lock
private object

Spot it when you see

  • `return self._items`
  • `this.items = items`
  • A setter per field
  • `if x.get() ... x.set()`
  • `register(this)` in a constructor
  • A test that edits what it got

Tricks that stick

  • PRIVATE: Private fields. Return copies. Input validation. Verify invariants. Accept copies. Type boundaries (immutable types). Expose behaviour, not data.
  • Bank vault: the teller checks, the ledger records, you get a receipt, not the ledger.
  • Ask of each line: is there now a second hand on my inside?

Do not forget

  • Copying strings and other immutable values
  • Check before copy
  • Shallow copies of changeable elements
  • Silent copies to old writers
  • Listeners called in the middle of a change
  • Believing TypeScript `private` at run time