Encapsulation
easy 35 minPut the data and the methods that work on it into one unit, and let outside code reach the data only through those methods.
Video lesson · Chapter 1 of 6
Make a prediction
See it run
Follow who touches the balance, and who is only allowed to ask.
Operations
The life of an object
Create, try the direct way, use a method, read, and be refused.
Step 1 of 5
Create
The constructor checks the holder and sets the balance to 0. All three fields are private, shown with a minus.
Step 1: Create
acc = BankAccount("John", "123")acc.balance_cents = 100000acc.deposit(50000)b = acc.balance_centsacc.deposit(-10000)- Good for
- State with rules
- Costs
- One method per action
Only one of these five lines changes the balance.
In the real world
The same encapsulation doing real jobs. Pick one and step through it.
Coins in by the slot, count by shaking, no hand inside.
Step 1 of 3
Slot
A coin goes in through the slot.
Step 1: Slot
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Public state with rules
criticalAny line of the program can break the rule.
Wrongaccount.balance -= 5000Rightaccount.withdraw(5000, day)Accessors by habit
majorA getter and a setter per field show the same structure as public fields.
Wrongset_health(get_health() - 30)Righttake_damage(30)Two copies of a rule
majorThe screen and the class will disagree after the next change.
Wrongif cents <= acc.balance_cents: ... # in the screenRightif acc.can_withdraw(cents, day): ...Order of checks
majorA negative amount is always smaller than the balance.
Wrongif cents <= self._balance: self._balance -= centsRightif cents <= 0: raise Refusedif cents > self._balance: raise RefusedA getter for a secret
criticalWhoever holds the PIN can log it, store it or send it.
Wrongif acc.get_pin() == typed:Rightif guard.matches(typed):Private as security
minorCode in the same process can go around it.
Wrong# safe, the field is privateRight# the server checks rights, the class keeps rules
Interview tips
Start with the rule
- Write it as a sentence
- Find the class that has the data
- Put the check there
Shape the public list
- Who calls this?
- Action or answer?
- Remove what nobody asks for
Prove it
- Swap the inside
- Run the same tests
- Count files per change
Know when not
- No rule: a plain record
- Constants may be public
- One file, one helper: keep it simple