Ensuring proper encapsulation
medium 40 minPrivate fields are the start, not the end.
Video lesson · Chapter 1 of 6
Make a prediction
See it run
Follow references, not names: who can still reach the inside?
Operations
A public field
Two jobs write the same number. Nobody checks.
Step 1 of 4
Start
A balance and two parts of the program that can name it.
Step 1: Start
class BankAccount: def __init__(self): self.balance = 0acc.balance = 500acc.balance = -1000- Good for
- Plain records
- Costs
- Every writer is a suspect
If a rule exists, a public field cannot keep it.
In the real world
The same ensuring proper encapsulation doing real jobs. Pick one and step through it.
The story again, as objects and calls.
Step 1 of 4
A crumb
Sam offers a crumb. The hatch lets it in.
Step 1: A crumb
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Returning the real list
criticalThe caller can clear it and no method of the class runs.
Wrongdef skills(self): return self._skillsRightdef skills(self): return tuple(self._skills)Keeping the caller's list
criticalThe caller still holds it and may share it with a second object.
Wrongself._members = membersRightself._members = list(members)Check before copy
majorThe object may change between the two lines.
Wrongif slot.start >= slot.end: raise ValueErrorself._slot = copy(slot)Rights, e = slot.start, slot.endif s >= e: raise ValueErrorself._slot = (s, e)Half a change on error
criticalThe first write stays when the second check fails.
Wrongself._count += 1if not ok(item): raise ValueErrorRightif not ok(item): raise ValueErrorself._count += 1Copies of immutable values
minorPython's
datetimeand strings cannot change. The copy protects nothing.Wrongself._hired = deepcopy(hired) # a datetimeRightself._hired = hiredSetter for everything
majorIt does not know why the value changes, so it cannot check or record.
Wronge.set_salary(8_250_000)Righte.give_raise(10)
Interview tips
Write the rules first
- Three invariants on the board
- Every door against each rule
- Then choose the methods
Follow references
- Who else holds this list?
- What can they do to it?
- Are the elements changeable too?
Prefer values
- Frozen dataclass, record
- `LocalDate`, not `Date`
- Then no copies
Know when not
- No invariant: a plain record
- Inside one module: ownership by contract
- Hot loop: measure first