AlgoViz

Ensuring proper encapsulation

medium 40 min

Private fields are the start, not the end.

Watch lesson4:46

Side doors

Seven ways around a perfect set of methods.

The point: look for every path on which a reference or a half built object can leave. Methods are only one of them.

The inspection list

DoorHow it opensHow to close it
Subclassprotected fields, overridden methods that skip the checkfinal class, private fields, small hooks. See Preventing subclassing
this escapesconstructor registers itself as a listener before it is finishedstatic factory: build, then register
Overridable call in the constructorsubclass method runs before its fields existcall only private or final methods there
Callbacka listener calls back while the state is half writtenfinish all writes, then notify from a copy of the listener list
Iterator or lambdaan inner iterator with remove, a closure over a fielditerate over a snapshot
Serialization, JSON, ORMfields are set by reflection, no constructor runsmap to a DTO and go through the constructor
Text outputtoString prints a token, an error contains the balanceprint an id, mask the rest
Static fieldstatic List CACHE is shared by all instancesprivate, immutable, or an injected object
Java records use their canonical constructor when they are deserialized. Ordinary serializable classes do not run their own constructor.

The callback that came too early

Python
class Early:    def __init__(self): self._total, self._lines, self._listeners = 0, [], []    def on_change(self, f): self._listeners.append(f)    def add(self, cents):        self._lines.append(cents)        for f in self._listeners: f(self)        # rule is false right now        self._total += centsclass Late(Early):    def add(self, cents):        self._lines.append(cents)        self._total += cents        for f in list(self._listeners): f(self)  # rule holds, and the list may changedef rule(c): print(type(c).__name__, "rule holds:", c._total == sum(c._lines))for cls in (Early, Late):    c = cls()    c.on_change(rule)    c.add(500)
Foreign code may only run when all invariants hold. A copy of the listener list also survives a listener that removes itself.
Edit and run it in your browser

The half built object

A reference leaves before the end

Use a factory method: create the Alarm completely, then register it, then return it.

What about reflection?

In most languages a determined caller can get in: reflection in Java, _Class__name in Python, a cast in C++. Encapsulation protects against mistakes and keeps the cost of change low. It is not a security border between programs. For untrusted code use a process or a sandbox. Java modules are the strong exception inside one process: since Java 17 deep reflection into JDK internals is refused by default.