Protecting State Invariants
Consider a BankAccount object. If its balance attribute is public, any rogue line of code could set account.balance = -999999 without triggering any security check.
class BankAccount:
def __init__(self, initial_deposit: float):
self._balance = max(0.0, initial_deposit) # Private internal state
def withdraw(self, amount: float) -> bool:
if 0 < amount <= self._balance:
self._balance -= amount
return True
return False # Invariant defended!
Quick Summary
- Encapsulation hides internal implementation details and exposes only safe public interfaces.
- Next, we explore Inheritance and its tradeoffs.