Ensuring proper encapsulation
medium 40 minPrivate 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)Rules and the doors that break them
| Rule | Door today | Door after |
|---|---|---|
| A name is never blank | constructor and field | checked in the constructor, no setter |
| Salary is whole cents, 0 or more | field, floats, NaN | integer cents, only give_raise |
| One raise is 0 to 50 percent | nothing | give_raise refuses |
| Every change of salary is recorded | nothing | give_raise writes both |
| Skills are lower case, not blank, unique | shared list | own list, add_skill cleans and checks |
| The hire date does not change | field | read only, and a date cannot change in Python |