AlgoViz

Ensuring proper encapsulation

medium 40 min

Private fields are the start, not the end.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:46

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

importImportJobwantswaitingadminAdminToolwantswaitingaccBankAccountbalance0entriesno history

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

Samvisitorhascrumbhatchpublic methodrulefood onlyfarmprivate statequeensafefood1 crumbput(crumb)thanks

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

    critical

    The caller can clear it and no method of the class runs.

    Wrong
    def skills(self):    return self._skills
    Right
    def skills(self):    return tuple(self._skills)
  • Keeping the caller's list

    critical

    The caller still holds it and may share it with a second object.

    Wrong
    self._members = members
    Right
    self._members = list(members)
  • Check before copy

    major

    The object may change between the two lines.

    Wrong
    if slot.start >= slot.end: raise ValueErrorself._slot = copy(slot)
    Right
    s, e = slot.start, slot.endif s >= e: raise ValueErrorself._slot = (s, e)
  • Half a change on error

    critical

    The first write stays when the second check fails.

    Wrong
    self._count += 1if not ok(item): raise ValueError
    Right
    if not ok(item): raise ValueErrorself._count += 1
  • Copies of immutable values

    minor

    Python's datetime and strings cannot change. The copy protects nothing.

    Wrong
    self._hired = deepcopy(hired)   # a datetime
    Right
    self._hired = hired
  • Setter for everything

    major

    It does not know why the value changes, so it cannot check or record.

    Wrong
    e.set_salary(8_250_000)
    Right
    e.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