9 min read Intermediate Lesson 2 of 9
Part 1 — Modeling Reality

Encapsulation

Encapsulation is not merely wrapping variables with getters and setters. It is the defensive engineering practice of Information Hiding to guarantee that an object's internal state can never be corrupted by outside code.

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.