AlgoViz

Ensuring proper encapsulation

medium 40 min

Private fields are the start, not the end.

Watch lesson4:46

Implementation

The class in three parts: birth, reads, changes.

The point: check at birth, share only what cannot change, and let each change do check, work, write in that order.

Employee, part by part

Employee

No half valid employee can exist. If the constructor returns, all rules hold.

from __future__ import annotationsfrom dataclasses import dataclassfrom datetime import date@dataclass(frozen=True)class Raise:    percent: int    before: int    after: intclass Employee:    MAX_RAISE = 50    def __init__(self, name: str, salary_cents: int, hired: date) -> None:        if not name or not name.strip():            raise ValueError("name is required")        if salary_cents < 0:            raise ValueError("salary cannot be negative")        self._name = name.strip()        self._salary_cents = salary_cents        self._hired = hired        self._skills: list[str] = []        self._raises: list[Raise] = []

Lines 6 to 10

A record of one raise, frozen. If it could change, the history would need copies of copies.

1 of 5

Why it is built this way

  • Skills are not a constructor argument: one way in is enough.
  • In TypeScript a Date can change, so that version copies it. Same rule, other answer.

What each line protects

If you dropThen
the check on nameblank names reach invoices
tuple(...)a template sorts the list and reorders the stored skills
frozen=Truea report rewrites history
the local aftertwo formulas that must agree
the capa typo of 500 for 50 is a salary times six