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.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:51

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

maincallergotnothingaccBankAccount- holderJohn- number123- balance0BankAccount(John)

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

childcallerhandemptypigPiggyBank- coins1deposit(coin)

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

    critical

    Any line of the program can break the rule.

    Wrong
    account.balance -= 5000
    Right
    account.withdraw(5000, day)
  • Accessors by habit

    major

    A getter and a setter per field show the same structure as public fields.

    Wrong
    set_health(get_health() - 30)
    Right
    take_damage(30)
  • Two copies of a rule

    major

    The screen and the class will disagree after the next change.

    Wrong
    if cents <= acc.balance_cents: ...   # in the screen
    Right
    if acc.can_withdraw(cents, day): ...
  • Order of checks

    major

    A negative amount is always smaller than the balance.

    Wrong
    if cents <= self._balance: self._balance -= cents
    Right
    if cents <= 0: raise Refusedif cents > self._balance: raise Refused
  • A getter for a secret

    critical

    Whoever holds the PIN can log it, store it or send it.

    Wrong
    if acc.get_pin() == typed:
    Right
    if guard.matches(typed):
  • Private as security

    minor

    Code in the same process can go around it.

    Wrong
    # safe, the field is private
    Right
    # 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