AlgoViz

Ensuring proper encapsulation

medium 40 min

Private fields are the start, not the end.

Watch lesson4:46

Copy, then check

Why the order of two lines decides whether the check means anything.

The point: check the thing you keep. If you check the caller's object and copy it afterwards, it may change in between.

The gap

Check first, copy later

Known as TOCTOU: time of check to time of use. The secure coding guidelines for Java say that input validation must occur after any defensive copying.

The meeting, sealed

Meeting

Read the foreign object once, into values. From then on it does not exist for us.

class Slot:    """A changeable pair of times, written by somebody else."""    def __init__(self, start: int, end: int) -> None:        self.start = start        self.end = endclass Meeting:    def __init__(self, slot: Slot, guests: list[str]) -> None:        start, end = slot.start, slot.end        people = tuple(guests)        if start >= end:            raise ValueError("start must be before end")        if not people:            raise ValueError("a meeting needs a guest")        self._start, self._end = start, end        self._guests = people

Lines 1 to 5

A changeable class that we do not own. In Java and TypeScript the same role is played by Date.

1 of 4

Why it is built this way

  • Do not use clone() on an argument whose class is not final: a subclass decides what it returns. Read the values out yourself.
  • The two reads slot.start, slot.end are still not one atomic step. The pair may mix two versions, but it is checked, so the invariant holds. If a consistent pair matters, ask the caller for an immutable value.

Prove that the order matters

Python
class Tricky:    """Answers differently on the second read, like an object changed by another thread."""    def __init__(self):        self.start, self.reads = 9, 0    @property    def end(self):        self.reads += 1        return 10 if self.reads == 1 else 8def check_then_copy(slot):    if slot.start >= slot.end: raise ValueError    return slot.start, slot.enddef copy_then_check(slot):    start, end = slot.start, slot.end    if start >= end: raise ValueError    return start, endprint("check then copy:", check_then_copy(Tricky()))print("copy then check:", copy_then_check(Tricky()))
One thread is enough to show it: a property that changes is the same as a neighbour that changes it.
Edit and run it in your browser

Alternatives

WayGoodCost
Copy, then checkworks with any argumentone copy per call
Take an immutable valueno copy, no gapcallers must build it
Take ownership by contractno copya comment is the only lock. Fine inside one module
Move semantics (C++, Rust)the compiler sees the transferin C++ the old name can still be used by mistake