Ensuring proper encapsulation
medium 40 minPrivate 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
1/3Five private fields
Two are changeable lists. They never leave as lists.
usesowns (dies together)
Public list, line by line
| Member | Why public | Why safe |
|---|---|---|
name, salary_cents, hired | shown on every page | strings, integers and dates cannot change |
skills, raises | listed on the profile | tuple: a snapshot of immutable elements |
has_skill | the real question of most callers | returns a bool, and no copy is made |
add_skill, give_raise | the only two changes | check, then write |
no set_salary | nobody has a reason that is not an action | if one appears, it gets a name: correct_salary(reason) |