LLD · 02 System Design: LLD

OOP in Practice: The Four Pillars

OOP in Practice: The Four Pillars

A payments app lets any code write wallet.balance, and it works, until a change request arrives: a refund must never take a balance below zero. We count six lines in four files that write the balance directly, and nothing at all stops wallet.balance = -500. Then we fix it with the four pillars of object-oriented programming, each one shown working on the same wallet, with real Python that runs and real tests that pass.

Chapters

Cheat sheet

Code

Four versions of one small wallet, each with its tests (Python 3.14, pytest, mypy): a public balance (5 passed); encapsulated, with the change request in one place (10 passed, the old test file untouched); a ledger inside with the callers byte-identical (12 passed); and an abstract PaymentMethod with Wallet, Card and GiftCard behind one checkout (26 passed, including one contract test suite run against all three).

Sources

Transcript

Here's a wallet class from a payments app: an owner, and a balance in whole cents. The balance is public: any code can read it, or change it. And plenty does. Checkout takes money from the buyer and gives it to the shop. A refund sends it back.

A payout moves the shop's money to its bank, and a support tool can set any balance by hand. It all works, and the tests pass. Then a change request arrives: a refund must never take a balance below zero. Here's why. Ana has eighty dollars.

She buys a fifty-dollar lamp from Ben's shop, and Ben moves forty dollars to his bank. Then Ana returns the lamp, and Ben's shop is at minus forty. So where does the rule go? We counted: six lines in four files write the balance directly, and only two of those files check it first. And nothing at all stops this.

This is Just Known. From unknown, to known. Episode two of our low-level design series: object-oriented programming in practice, the four pillars. This whole episode, in one sentence: an object owns its data, and the rules about that data. A rule that must always hold for an object is called an invariant.

For our wallet: the balance is never below zero. Not after checkout, not after a refund, not ever. The idea is older than Python. In 1972, David Parnas argued that each module should hide a design decision that's likely to change, behind an interface that reveals as little as possible about how it works inside. Encapsulation applies that idea to a single object.

It's the first of four pillars, and we'll build all four on this wallet. First, two words we'll use all episode. A class is a blueprint: it says what every wallet has, and what it can do. An object is one wallet built from it, with its own data. Ana's wallet and the shop's wallet are two objects of the same class, each with its own balance.

In a diagram, a class box has its name on top. An object's box has its name underlined, then the class after a colon, then its own values. The first pillar is encapsulation, and step one is hiding the data. In Python, that's a naming convention: a leading underscore, as in underscore balance, means internal, so don't touch it from outside. But it's a sign, not a lock.

Code outside can still set underscore balance to minus five hundred, and Python lets it. Two underscores go further: Python renames the attribute, putting the class name in front. That's name mangling. It prevents accidental clashes in subclasses, but the value is still there, under its new name. Python has no truly private attributes.

It trusts you to read the sign. Step two is a safe way in. The balance becomes a property: the property decorator turns a method into a read-only attribute. Callers still read wallet dot balance, as before. But there's no setter, so assigning to it fails: property balance of Wallet object has no setter.

The only way to change the balance is through two methods. Deposit adds money. Pay takes it out, and it's the one place that checks the rule: if there isn't enough, it raises insufficient funds, and nothing changes. Inside pay, self is the wallet it was called on. Both methods also check the amount: whole, positive cents.

Never a float, because floats can't store most decimal fractions exactly: zero point one plus zero point two isn't zero point three. Now the change request lands in one place. Checkout, refunds, payouts and the support tool all call deposit and pay, instead of writing the balance. Count again: outside the wallet, nothing writes the balance, and the check exists exactly once, inside pay. So the cold open replays like this: after the lamp and the payout, the shop has ten dollars.

The refund asks it to pay fifty, so it refuses, and nothing moves. Getting here touched every caller once: that's the price of starting with a public field. But the five old tests pass without a single edit, five new ones guard the rules, and all ten pass. Run the new tests against the old public wallet, and all five fail. The second pillar is abstraction: callers know what an object does, not how it does it.

Checkout knows a wallet has a balance, takes deposits, and pays. How the balance is stored is none of its business. Let's prove it. Support now wants every change on record, so the inside becomes a ledger: a list of entries, money in and money out. The balance isn't stored anymore; it's the sum of the entries.

And the history goes out as a tuple, a copy nobody can change. The callers are identical files. The ten old tests are identical too, two new ones cover the history, and all twelve pass. Encapsulation guards the data. Abstraction lets you rebuild the inside without anyone noticing.

Customers can now also pay by card or with a gift card. All three are payment methods, so they share one base class. Payment method is an abstract base class, from Python's A B C module. Its pay method is marked abstract: every subclass must write its own. The amount check moves up into the base, so subclasses inherit it.

Python enforces this when an object is created. Make a payment method itself, or a coupon that forgot pay, and you get a type error: can't instantiate abstract class. It only checks names, though: a pay that forgets its amount gets through. The idea goes back to Simula 67, by Ole-Johan Dahl and Kristen Nygaard: put what different classes have in common into one class, and let subclasses inherit it. Use inheritance when one thing really is a kind of another.

For sharing code between things that aren't, episode seven has a better tool. The fourth pillar is polymorphism: one call, many behaviors. Checkout's body didn't change at all; only its type hint widened, from a wallet to any payment method. Now run it three times, fifty dollars each. Ana's wallet pays from its balance.

The card adds the charge to what it has spent, within its limit. The gift card has only twenty-five dollars, so it refuses. Same line of code, and each object brings its own pay. The shop collects one hundred dollars, and checkout never asked what kind of payment method it was holding. Python adds a twist: it never checks type hints while the code runs.

Here's a voucher class from another team. It has a pay method, but doesn't inherit from payment method. Pass it to checkout anyway, and it works. That's duck typing: if it has the method you call, it fits. A type checker reads the hints before anything runs, and it rejects the voucher: incompatible type.

To let outside classes in, describe the shape, not the family. A protocol says: anything with a pay method that takes an amount. The type checker accepts the voucher, no inheritance needed, and rejects a broken class whose pay forgot the amount. One trap: runtime checkable lets is instance test a protocol at run time, but it only checks that a method with that name exists. The broken class passes, then crashes when it's called.

Here's checkout running, as a sequence diagram. Ana's wallet first. Checkout calls pay. The wallet checks the amount with the check it inherited, then checks the rule: is there enough? There is, so it records the payment, and checkout deposits the money in the shop's wallet.

Now the gift card. Same call, but this time pay runs the gift card's own code. Fifty dollars is more than it has left, so it raises payment failed, and checkout stops right there. The deposit never happens: no money appears, and none disappears. Now the tests: twenty-six, in four files.

Three files come from earlier versions, unchanged. The new file is a contract. One fixture hands each test a wallet, a card and a gift card in turn, each able to cover exactly fifty dollars. Each must pay up to that, refuse one cent more, take nothing when it refuses, reject a bad amount, and work with checkout. Four tests, three methods: twelve runs.

A new payment method needs one more line in that fixture. And a subclass that can't pass its parent's tests isn't a real substitute: that's episode six. Two more tests check that the base class, and a subclass without pay, can't be created. All twenty-six pass. Like any tool, these can be overdone.

First, don't write a getter and a setter for every field. In Python, start with a plain attribute, like the owner. If a rule shows up later, make it a property, and callers don't change: our payment-flow tests read wallet dot balance in all four versions, and that file never changed. Second, keep inheritance shallow. A subclass depends on its parent's details, so every change to a parent ripples down the tree.

A gift card looks a lot like a wallet, but if it inherited from wallet, it would get deposit too, and gift cards can't be topped up. Third, the underscore isn't security. It stops accidents, not attackers. You've used all four pillars already. Len works on a list, a string and a dictionary, because each type brings its own dunder len method: polymorphism.

The collections dot A B C module is full of abstract base classes: inherit from sequence, write two methods, and get five more free, like index and reversed. And print writes to anything with a write method, a file or a string buffer: duck typing. On Android, Kotlin makes a setter private in two words: private set. Kotlin's own docs use it on a bank account's balance, and Android's guides use it to keep a view model's state read-only for the UI. And a RecyclerView gets its rows from an adapter, an abstract class you subclass by writing three methods.

Interview corner. What are the four pillars of object-oriented programming? And how would you make sure a wallet's balance can never go below zero? Pause here, and try answering in thirty seconds.

Here's a strong answer. Encapsulation: an object owns its data and guards its invariants, so the balance is private, readable through a property, and changed only by methods that check it. Abstraction: callers depend on what it does, deposit and pay, not on how it's stored. Inheritance: share a contract and code when one thing is a kind of another. Polymorphism: one call, and each object runs its own version.

To stand out, say the invariant out loud, test the edge, one cent over, and know where Python differs: the underscore is a convention, and a protocol checks shape, not family. Let's recap. An object owns its data and its rules, so a change request like ours lands in one place. Abstraction lets you rebuild the inside without touching a single caller. And inheritance shares a contract, while polymorphism lets one line of code work with every class that keeps it.

Next, we'll draw all of this properly: every box, and every arrow. That's episode three: reading and drawing class diagrams. This is Just Known. From unknown, to known.

Note: Ana, Ben's shop and Chen are made-up examples; every line of code, test and output on screen is from a real run (Python 3.14.3, pytest 9.2.0, mypy 2.4.1). Pictures marked "illustration" are not real output.
Narration voice generated with Google Gemini text-to-speech.