Ensuring proper encapsulation
medium 40 minPrivate 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
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 = peopleLines 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.endare 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()))Alternatives
| Way | Good | Cost |
|---|---|---|
| Copy, then check | works with any argument | one copy per call |
| Take an immutable value | no copy, no gap | callers must build it |
| Take ownership by contract | no copy | a comment is the only lock. Fine inside one module |
| Move semantics (C++, Rust) | the compiler sees the transfer | in C++ the old name can still be used by mistake |