AlgoViz

Ensuring proper encapsulation

medium 40 min

Private fields are the start, not the end.

Watch lesson4:46

Problem

An Employee class that everybody can corrupt, and the list of rules it should keep.

The point: before hiding anything, write down what must always be true. Encapsulation is the tool that keeps these sentences true.

The class we get

Python
class Employee:    def __init__(self, name, salary, hired, skills):        self.name = name        self.salary = salary        self.hired = hired        self.skills = skillsshared = ["python"]a = Employee("", 75_000.0, None, shared)b = Employee("Lee", 60_000.0, None, shared)a.skills.append("juggling")          # meant for one personb.salary = float("nan")              # 'nan < 0' is False, so a naive check would pass tooprint(repr(a.name), b.skills, b.salary < 0, b.salary)
No name, a skill on the wrong person, and a salary that is not a number.
Edit and run it in your browser

Rules and the doors that break them

RuleDoor todayDoor after
A name is never blankconstructor and fieldchecked in the constructor, no setter
Salary is whole cents, 0 or morefield, floats, NaNinteger cents, only give_raise
One raise is 0 to 50 percentnothinggive_raise refuses
Every change of salary is recordednothinggive_raise writes both
Skills are lower case, not blank, uniqueshared listown list, add_skill cleans and checks
The hire date does not changefieldread only, and a date cannot change in Python