LLD

Design Principles

Encapsulation

A class should keep its data and the rules about that data together, and outside code should change the data only through methods that follow those rules. We build a prepaid wallet twice, once with a setter for the balance and once with credit and debit, and add a KYC limit to each.

A prepaid wallet in a phone app holds money for small payments. We add $500 from UPI (Unified Payments Interface), pay $120 at a grocery shop and get $20 back as cashback. Two rules hold the whole time: the balance never goes below zero, and every dollar that comes in or goes out has a line in the history.

Encapsulation says that a class keeps its data and the rules about that data together, and outside code changes the data only through methods that follow those rules.

The principle

A rule that must always hold for an object is called an invariant. The wallet has two: the balance is never negative, and the balance equals the sum of the history. Encapsulation puts the code that changes the balance in the same class as these rules. A caller asks the wallet to do something, like take $120, and the wallet decides whether it can.

The common misreading is that encapsulation means private fields with a getter and a setter for each. A public setter lets any caller write any value, just like a public field. The field is private, but the rule is not protected. The test is this: can a caller put the object into a state that breaks its rules? If it can, the data is not encapsulated, however private the fields are.

A setter is a public field
A private field with a public setter protects the balance no better than a public field. Each column starts from a wallet holding $400, and a caller tries to leave it at -$500. The public field and the setter both accept the value, in red. Only debit(), which checks the balance before it changes it, refuses, and the balance stays $400, in purple.A private field with a public setter protects the balance no better than a public field. Each column starts from a wallet holding $400, and a caller tries to leave it at -$500. The public field and the setter both accept the value, in red. Only debit(), which checks the balance before it changes it, refuses, and the balance stays $400, in purple.
Three ways to let callers change the balance, and what each does with a bad request. A private field with a public setter protects the balance no better than a public field. Each column starts from a wallet holding $400, and a caller tries to leave it at -$500. The public field and the setter both accept the value, in red. Only debit(), which checks the balance before it changes it, refuses, and the balance stays $400, in purple.

Encapsulation does not mean hiding every value either. The wallet still shows its balance. A getter is fine as long as a caller cannot change the object through what it returns.

Example: a prepaid wallet

The first version has a private balance, a getter and a setter:

import java.util.ArrayList;import java.util.List; public class Wallet {    private long balance;    private final List<Transaction> history = new ArrayList<>();     public long getBalance() {        return balance;    }     public void setBalance(long balance) {        this.balance = balance;    }     public List<Transaction> getHistory() {        return history;    }}

Transaction is a record with a note and an amount.

The rules now live in the callers. ShopPayment checks the balance, takes the amount and writes the history line. CashbackService adds the cashback and forgets the history line:

class ShopPayment {    void pay(Wallet wallet, long amount) {        long balance = wallet.getBalance();        if (balance >= amount) {            wallet.setBalance(balance - amount);            wallet.getHistory().add(new Transaction("Shop payment", -amount));        }    }} class CashbackService {    void reward(Wallet wallet, long cashback) {        wallet.setBalance(wallet.getBalance() + cashback);    }}

A third caller, UpiTopUp, adds money from a bank account and does write the history line. Nothing stops a fourth caller from calling setBalance(-500).

Then a change request arrives. A wallet whose owner has not finished the full know-your-customer (KYC) checks may hold at most $10,000. Every caller that adds money must now check this limit: UpiTopUp and CashbackService today, and any caller added later, such as refunds. If one of them forgets, the limit is broken, and Wallet cannot notice.

Every caller holds the rules
When the class holds no rules, every caller must carry them, and a new rule goes into every caller. Wallet has a getter and a setter and checks nothing. UpiTopUp and CashbackService both add money, so the new $10,000 limit, in amber, must be added to both. CashbackService already writes no history line, in red, and any caller can set the balance to -$500.When the class holds no rules, every caller must carry them, and a new rule goes into every caller. Wallet has a getter and a setter and checks nothing. UpiTopUp and CashbackService both add money, so the new $10,000 limit, in amber, must be added to both. CashbackService already writes no history line, in red, and any caller can set the balance to -$500.
The wallet only stores numbers, so each caller carries its own copy of the rules. When the class holds no rules, every caller must carry them, and a new rule goes into every caller. Wallet has a getter and a setter and checks nothing. UpiTopUp and CashbackService both add money, so the new $10,000 limit, in amber, must be added to both. CashbackService already writes no history line, in red, and any caller can set the balance to -$500.

Moving the rules into the wallet

We remove the setter and give the wallet two methods that change the balance, credit and debit. Each one checks its rule, changes the balance and writes the history line, in one place:

import java.util.ArrayList;import java.util.List; public class Wallet {    private long balance;    private final List<Transaction> history = new ArrayList<>();     public void debit(long amount, String note) {        requirePositive(amount);        if (amount > balance) {            throw new IllegalStateException("Insufficient balance");        }        balance -= amount;        history.add(new Transaction(note, -amount));    }     public List<Transaction> getHistory() {        return List.copyOf(history);    }}

credit has the same shape. We show it below, with the new limit.

requirePositive is a private helper that refuses zero and negative amounts, so debit(-500, ...) cannot add money. getBalance() still returns the balance. getHistory() now returns a copy, so a caller cannot add a fake line to the real list. The Iterator pattern page shows what goes wrong when a getter hands out the real list.

Each caller is now one line, such as wallet.debit(amount, "Shop payment"), and the checks that ShopPayment used to do are gone from it.

Now the same change again. The limit is one check inside credit, and the wallet gets a fullKyc field, set in its constructor:

    private static final long LIMIT_WITHOUT_FULL_KYC = 10_000;     private final boolean fullKyc;     public Wallet(boolean fullKyc) {        this.fullKyc = fullKyc;    }     public void credit(long amount, String note) {        requirePositive(amount);        if (!fullKyc && amount > LIMIT_WITHOUT_FULL_KYC - balance) {            throw new IllegalStateException("Wallets without full KYC can hold up to $10,000");        }        balance = Math.addExact(balance, amount);        history.add(new Transaction(note, amount));    }

Math.addExact throws on overflow instead of wrapping the balance round to a negative number.

The rules live in the wallet
When the class owns its rules, a new rule is one edit in that class. The three callers call credit() or debit(), and the limit change does not touch them. Wallet has an amber outline because the limit check is added to credit(). Every credit and debit creates a Transaction record, in orange, for the history, so no caller can skip the history line.When the class owns its rules, a new rule is one edit in that class. The three callers call credit() or debit(), and the limit change does not touch them. Wallet has an amber outline because the limit check is added to credit(). Every credit and debit creates a Transaction record, in orange, for the history, so no caller can skip the history line.
After the change, each caller makes one call, and the new limit is one check in Wallet. When the class owns its rules, a new rule is one edit in that class. The three callers call credit() or debit(), and the limit change does not touch them. Wallet has an amber outline because the limit check is added to credit(). Every credit and debit creates a Transaction record, in orange, for the history, so no caller can skip the history line.

No caller's code changed. A caller only decides what to do when the wallet refuses. A refund added next month calls credit and gets the limit without knowing it exists.

When not to

Some classes have no rules to protect. Transaction is a record: its fields are final, and any note with any amount is a valid history line, so public accessors are fine. The same holds for a request object that only carries data from the app to the server. Methods that guard the fields of such a class add code and protect nothing. We encapsulate data that has a rule, not every class by habit.

In an interview

When you draw a class that holds state, name its rule and the methods that change the state. Leave out setters on classes that have rules, and say why. In the Splitwise design, only Group writes the balances, and it refuses any expense that would stop them adding up to zero.

Common mistakes:

  • A getter and a setter for every field. The setter is a public field with a longer name.
  • Checking the rule in the caller. The balance >= amount check in ShopPayment is a rule the wallet should own.
  • A getter that returns the live list. Any caller can then add or remove history lines.

Summary

  • Encapsulation keeps data and its rules in one class, and outside code changes the data only through that class's methods.
  • Private fields with public setters are not encapsulation, because a caller can still break the object's rules through them.
  • When the class owns its rules, a new rule goes into one method, and no caller changes.

Spot a mistake, or something unclear? . Or get in touch.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.