AlgoViz

Encapsulation

easy 35 min

Put the data and the methods that work on it into one unit, and let outside code reach the data only through those methods.

Watch lesson4:51

Problem

A bank account with public fields, and rules that live in three other classes.

The point: find the rules first. Encapsulation means moving them to the class that has the data.

The code we get

Python
class BankAccount:    def __init__(self, holder, number):        self.holder, self.number, self.balance = holder, number, 0.0def pay_out(account, amount):                # in the cash machine    if amount <= account.balance:            # the limit is missing here        account.balance -= amountdef web_transfer(a, b, amount):              # in the web shop    if 0 < amount <= a.balance:        a.balance -= amount        b.balance += amountjohn, jane = BankAccount("John", "123456"), BankAccount("Jane", "654321")john.balance = 500.0pay_out(john, -100)                          # a negative amount prints moneyprint(john.balance)print(0.1 + 0.2 == 0.3)                      # and float money does not add up
Two writers, two versions of the rule. One forgot that amounts are positive.
Edit and run it in your browser

Where each rule lives

RuleTodayAfter
An amount is positiveweb shop onlydeposit and withdraw
The balance is never below zerotwo copiesone private check
At most 500.00 a daynowheresame private check
A frozen account pays nothingnowheresame private check
Money is exactfloatwhole cents
The full number is not shownevery page decidesmasked_number