AlgoViz

Ensuring proper encapsulation

medium 40 min

Private fields are the start, not the end.

Watch lesson4:46

UML design

Which members are public, and what type leaves the class.

The point: the public list is the contract. Write it as short as the callers allow, and check the type of everything that leaves.

Employee, sealed

Employee- name: str- salary_cents: int- hired: date- skills: list[str]- raises: list[Raise]+ name, salary_cents, hired+ skills: tuple[str, ...]+ raises: tuple[Raise, ...]+ has_skill(s): bool+ add_skill(s)+ give_raise(percent)

1/3Five private fields

Two are changeable lists. They never leave as lists.

usesowns (dies together)

Public list, line by line

MemberWhy publicWhy safe
name, salary_cents, hiredshown on every pagestrings, integers and dates cannot change
skills, raiseslisted on the profiletuple: a snapshot of immutable elements
has_skillthe real question of most callersreturns a bool, and no copy is made
add_skill, give_raisethe only two changescheck, then write
no set_salarynobody has a reason that is not an actionif one appears, it gets a name: correct_salary(reason)