These are the notes for Low-Level Design (LLD) episode 17. SOLID is done; these are the other principles every good designer carries around: DRY, KISS, YAGNI, the Law of Demeter, the nine GRASP principles, and the principle of least astonishment. Each one arrives the usual way: something breaks first, in a college canteen app. Every program was run with javac Main.java && java -cp . Main (Java 21); outputs and error messages are real.
1. The real-life problem: one rule, three notice boards
A college writes the canteen timings on three notice boards: at the gate, the library and the canteen. The timings change to 9 am; the peon updates one board and forgets the other two. Now students argue about which board is right. Copies of a fact always drift apart. The fix: one screen with the timings, and everything else points to it.
2. DRY: don't repeat yourself
The canteen app types the tax rate into three classes. The rate changes to 12%; only Bill gets updated (the rates here are made-up examples, not real tax rates):
class Bill {
double total(double amount) { return amount + amount * 0.12; } // tax rate changed to 12%
}
class Invoice {
double total(double amount) { return amount + amount * 0.18; } // copy 2: forgotten
}
class Receipt {
double tax(double amount) { return amount * 0.18; } // copy 3: forgotten
}
public class Main {
public static void main(String[] args) {
double meal = 100;
System.out.println("Bill shows: " + new Bill().total(meal));
System.out.println("Invoice shows: " + new Invoice().total(meal));
System.out.println("Receipt tax: " + new Receipt().tax(meal));
}
}
Bill shows: 112.0
Invoice shows: 118.0
Receipt tax: 18.0
Same meal, two totals, and no error: just wrong numbers. The fix gives the knowledge one home:
final class Tax { // the ONE place that knows the rate
static final double RATE = 0.12;
static double tax(double amount) { return amount * RATE; }
static double withTax(double amount) { return amount + tax(amount); }
}
class Bill { double total(double amount) { return Tax.withTax(amount); } }
class Invoice { double total(double amount) { return Tax.withTax(amount); } }
class Receipt { double tax(double amount) { return Tax.tax(amount); } }
public class Main {
public static void main(String[] args) {
double meal = 100;
System.out.println("Bill shows: " + new Bill().total(meal));
System.out.println("Invoice shows: " + new Invoice().total(meal));
System.out.println("Receipt tax: " + new Receipt().tax(meal));
}
}
Bill shows: 112.0
Invoice shows: 112.0
Receipt tax: 12.0
DRY (Andy Hunt and Dave Thomas, The Pragmatic Programmer, 1999):
Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.
Code that breaks it is jokingly called WET ("write everything twice", "we enjoy typing").
DRY is about knowledge, not text
Two lines that look the same but change for different reasons are not duplication. A delivery fee of Rs 20 and a packing fee of Rs 20 are two different facts; merging them into one constant means a change to one silently changes the other. (Same idea as "actors" in the Single Responsibility episode.)
| Real duplication (fix it) | Accidental similarity (leave it) |
|---|---|
| The tax rate typed in 3 classes | DELIVERY_FEE = 20 and PACKING_FEE = 20 |
| The same validation rule in the form and the API | Two loops that happen to look alike |
3. KISS: keep it simple, stupid
The delivery rule: free from Rs 500, Rs 20 from Rs 200, otherwise Rs 40. Someone wrote it as a clever one-line nested ternary (the condition ? ifTrue : ifFalse operator, used inside itself):
public class Main {
// rule: free delivery from Rs 500; Rs 20 from Rs 200; otherwise Rs 40
static int clever(int total) { return total > 500 ? 0 : total > 200 ? 20 : 40; }
static int simple(int total) {
if (total >= 500) return 0;
if (total >= 200) return 20;
return 40;
}
public static void main(String[] args) {
for (int t : new int[] { 150, 200, 499, 500 })
System.out.println("Rs " + t + " -> clever: " + clever(t) + ", simple: " + simple(t));
}
}
Rs 150 -> clever: 40, simple: 40
Rs 200 -> clever: 40, simple: 20
Rs 499 -> clever: 20, simple: 20
Rs 500 -> clever: 20, simple: 0
At exactly Rs 200 and Rs 500 the clever version is wrong: it used > where the rule says "from" (>=). In one dense line nobody spotted it; in the simple version each rule is its own line and can be checked in seconds.
KISS is linked to Kelly Johnson, lead engineer at Lockheed's Skunk Works (the team behind the U-2 and SR-71 spy planes). The story goes that he gave his designers a handful of tools and required that the jet be repairable by an average mechanic in the field with only those tools. The "stupid" isn't an insult: it's about the person who has to fix it later. In code: the most boring solution that works. Code is read far more often than it is written.
4. YAGNI: you aren't gonna need it
The canteen only takes rupees, but a developer builds a currency plug-in framework "in case we go international". Two years later: still rupees, and every change has to go through the framework.
YAGNI comes from extreme programming (XP), a software-development style built on short steps, constant testing and frequent releases. Ron Jeffries, one of its founders:
Always implement things when you actually need them, never when you just foresee that you need them.
Every extra feature costs time to write, test, read and change, even if nobody uses it. But YAGNI is not permission for messy code: keep the design clean (SOLID), so adding the feature later is cheap.
| YAGNI says build it now | YAGNI says wait |
|---|---|
| It's in this sprint's requirements | "What if we need X someday?" |
| The cost of adding it later is huge (e.g. a data format already shipped) | A plug-in system with one plug-in |
5. The Law of Demeter
An Order has a Customer, a Customer has a Wallet, the wallet has a balance. The checkout reaches through all three. Calls chained like this, a.getB().getC().doIt(), are called a train wreck (they look like train coaches).
class Wallet {
private int balance = 300;
int getBalance() { return balance; }
void setBalance(int b) { balance = b; }
}
class Customer {
private final Wallet wallet = new Wallet();
Wallet getWallet() { return wallet; }
}
class Order {
private final Customer customer = new Customer();
Customer getCustomer() { return customer; }
}
public class Main {
public static void main(String[] args) {
Order order = new Order();
int price = 120;
// the checkout reaches through three objects: a train wreck
Wallet w = order.getCustomer().getWallet();
if (w.getBalance() >= price) w.setBalance(w.getBalance() - price);
System.out.println("Left in wallet: " + order.getCustomer().getWallet().getBalance());
}
}
Left in wallet: 180
It works, until the wallet team changes how money is stored. They edit only Wallet; the checkout code is identical:
import java.util.*;
class Wallet { // changed: now money lives in UPI accounts
private final List<Integer> upiAccounts = new ArrayList<>(List.of(200, 100));
List<Integer> getUpiAccounts() { return upiAccounts; }
}
class Customer {
private final Wallet wallet = new Wallet();
Wallet getWallet() { return wallet; }
}
class Order {
private final Customer customer = new Customer();
Customer getCustomer() { return customer; }
}
public class Main { // checkout code: not touched
public static void main(String[] args) {
Order order = new Order();
int price = 120;
Wallet w = order.getCustomer().getWallet();
if (w.getBalance() >= price) w.setBalance(w.getBalance() - price);
}
}
Main.java:20: error: cannot find symbol
if (w.getBalance() >= price) w.setBalance(w.getBalance() - price);
^
symbol: method getBalance()
location: variable w of type Wallet
Main.java:20: error: cannot find symbol
if (w.getBalance() >= price) w.setBalance(w.getBalance() - price);
^
symbol: method getBalance()
location: variable w of type Wallet
2 errors
A change deep inside the wallet broke the checkout, two objects away.
The rule
Proposed by Ian Holland at Northeastern University in 1987 (the Demeter project). A method m of an object may call methods only on:
- its own object (
this), m's parameters,- objects
mcreates, - the object's own fields,
- (and globals in scope).
Not on objects returned by those. Short forms: "only talk to your immediate friends", "don't talk to strangers", "use only one dot". Its other name is the principle of least knowledge: an object should assume as little as possible about how other objects are built inside.
Exception: fluent APIs such as builders and streams (list.stream().filter(...).map(...)) return the same kind of object at each step; they're not train wrecks.
The fix: tell, don't ask
import java.util.*;
class Wallet {
private final List<Integer> upiAccounts = new ArrayList<>(List.of(200, 100));
boolean pay(int amount) { // the wallet knows how its money is kept
for (int i = 0; i < upiAccounts.size(); i++)
if (upiAccounts.get(i) >= amount) { upiAccounts.set(i, upiAccounts.get(i) - amount); return true; }
return false;
}
}
class Customer {
private final Wallet wallet = new Wallet();
boolean pay(int amount) { return wallet.pay(amount); } // talk to your friend only
}
class Order {
private final Customer customer = new Customer();
private final int price;
Order(int price) { this.price = price; }
String checkout() { return customer.pay(price) ? "Paid Rs " + price : "Payment failed"; }
}
public class Main {
public static void main(String[] args) {
System.out.println(new Order(120).checkout());
System.out.println(new Order(900).checkout());
}
}
Paid Rs 120
Payment failed
Real-life version: a cashier doesn't grab your wallet and count your cash; she says "please pay 120" and you decide how.
6. GRASP: who gets which job?
A responsibility is something a class must know or do. GRASP, General Responsibility Assignment Software Patterns, is Craig Larman's set of nine principles for assigning responsibilities, from his book Applying UML and Patterns.
Information expert, creator, controller in code
import java.util.*;
class CartItem {
final String name; final int price, qty;
CartItem(String name, int price, int qty) { this.name = name; this.price = price; this.qty = qty; }
int subtotal() { return price * qty; } // expert: it has price and qty
}
class Cart {
private final List<CartItem> items = new ArrayList<>();
void add(String name, int price, int qty) { items.add(new CartItem(name, price, qty)); } // creator
int total() { return items.stream().mapToInt(CartItem::subtotal).sum(); } // expert
}
class CheckoutController { // controller: handles the "checkout" event
private final Cart cart;
CheckoutController(Cart cart) { this.cart = cart; }
String onCheckoutClicked() { return "Pay Rs " + cart.total(); }
}
public class Main {
public static void main(String[] args) {
Cart cart = new Cart();
cart.add("Samosa", 20, 3);
cart.add("Cold coffee", 90, 2);
System.out.println(new CheckoutController(cart).onCheckoutClicked());
}
}
Pay Rs 240
- Information expert: give a responsibility to the class that has the information to fulfil it.
CartItemhas price and quantity, so it computessubtotal();Carthas the items, so it computestotal(). - Creator: class B should create objects of class A if B contains, aggregates, closely uses, or has the initializing data for A.
Cartcontains its items, soCart.addcreates eachCartItem. - Controller: the first object behind the user interface that receives a system event (a click, a request) and delegates the work. It coordinates; it doesn't do the work.
CheckoutController.
The other six
| Principle | Meaning | Where we've met it |
|---|---|---|
| Low coupling | Keep dependencies few and loose, so changes have less impact | Episode 10 |
| High cohesion | The responsibilities inside one class belong together | Episodes 10, 12 |
| Polymorphism (GRASP) | When behaviour varies by type, let each type implement it, instead of if/switch on the type |
Episode 9 |
| Protected variations | Wrap the parts likely to change behind a stable interface | Episode 13 (open-closed) |
| Indirection | Put a middleman between two classes so they don't depend on each other directly | Episode 16 (Notifier), controllers |
| Pure fabrication | Invent a class that isn't a real-world concept, to keep coupling low and cohesion high | Tax, repositories, ReceiptPrinter |
7. The principle of least astonishment
A cart has a method named getTotal(). It adds the prices, and then clears the cart:
import java.util.*;
class Cart {
private final List<Integer> prices = new ArrayList<>(List.of(60, 180, 120));
int getTotal() { // looks like a question...
int sum = 0;
for (int p : prices) sum += p;
prices.clear(); // ...but secretly empties the cart
return sum;
}
}
public class Main {
public static void main(String[] args) {
Cart cart = new Cart();
System.out.println("Total on screen: " + cart.getTotal());
System.out.println("Total at payment: " + cart.getTotal());
}
}
Total on screen: 360
Total at payment: 0
A method named like a question secretly changed things. The principle of least astonishment (or least surprise): a component should behave the way most people reading it would expect. It's old: the "Law of Least Astonishment" appeared in the PL/I Bulletin in 1967.
getX(),isX(),size()only read.- A method that changes things says so:
checkout(),clear(),add(). - Familiar names keep their familiar meaning:
equalscompares,closecloses.
The fix separates the question from the action:
import java.util.*;
class Cart {
private final List<Integer> prices = new ArrayList<>(List.of(60, 180, 120));
int getTotal() { // a query: only reads
int sum = 0;
for (int p : prices) sum += p;
return sum;
}
int checkout() { // a command: the name says it changes things
int total = getTotal();
prices.clear();
return total;
}
}
public class Main {
public static void main(String[] args) {
Cart cart = new Cart();
System.out.println("Total on screen: " + cart.getTotal());
System.out.println("Total at payment: " + cart.getTotal());
System.out.println("Charged: " + cart.checkout() + ", left: " + cart.getTotal());
}
}
Total on screen: 360
Total at payment: 360
Charged: 360, left: 0
(Episode 51 names this command-query separation.)
The class diagram
«controller» CheckoutController ──uses──▶ Cart ◆──creates──▶ * CartItem
┊
┊uses
▼
«pure fabrication» Tax
Order ──pay()──▶ Customer ──▶ Wallet (each talks only to its direct friend)
Common mistakes
| Mistake | Exact message / symptom | Why | Fix |
|---|---|---|---|
| Tax rate typed in 3 classes | Bill shows: 112.0 / Invoice shows: 118.0 |
Copied knowledge drifted (not DRY) | One Tax class |
| Merging two equal-looking constants | no error: one change silently changes the other | DRY is about knowledge, not text | Keep separate facts separate |
total > 500 ? 0 : total > 200 ? 20 : 40 |
Rs 500 -> clever: 20 |
Too clever to check (not KISS) | Plain if statements |
| A framework for a feature nobody asked for | no error: time spent, code to maintain | Not YAGNI | Build it when it's needed |
order.getCustomer().getWallet().getBalance() |
cannot find symbol ... symbol: method getBalance() |
Talked to strangers (Demeter) | customer.pay(amount) |
getTotal() { ... prices.clear(); } |
Total at payment: 0 |
A surprising side effect | Reads only read; checkout() changes |
Mini project
Write a canteen checkout that uses every principle from this episode: one home for the fee rules (DRY, pure fabrication), plain fee logic (KISS), a cart that creates its items and computes its total (creator, expert), a customer that pays for itself (Demeter), and a controller that receives the click.
Solution
import java.util.*;
final class Fees { // DRY + pure fabrication: the one home for fee rules
static final int FREE_FROM = 500, LOW_FROM = 200;
static int delivery(int total) { // KISS: one rule per line
if (total >= FREE_FROM) return 0;
if (total >= LOW_FROM) return 20;
return 40;
}
}
class Item {
final String name; final int price;
Item(String name, int price) { this.name = name; this.price = price; }
}
class Cart {
private final List<Item> items = new ArrayList<>();
void add(String name, int price) { items.add(new Item(name, price)); } // creator
int subtotal() { int s = 0; for (Item i : items) s += i.price; return s; } // information expert
int payable() { return subtotal() + Fees.delivery(subtotal()); }
}
class Customer {
private int walletBalance;
Customer(int balance) { walletBalance = balance; }
boolean pay(int amount) { // Demeter: callers ask, the customer decides
if (amount > walletBalance) return false;
walletBalance -= amount; return true;
}
}
class CheckoutController { // controller: receives the event, delegates
String onPayClicked(Cart cart, Customer c) {
int amount = cart.payable();
return c.pay(amount) ? "Paid Rs " + amount : "Not enough balance for Rs " + amount;
}
}
public class Main {
public static void main(String[] args) {
Cart small = new Cart(); small.add("Chai", 15); small.add("Samosa", 20);
Cart big = new Cart(); big.add("Thali", 220); big.add("Lassi", 80); big.add("Kulfi", 200);
CheckoutController ctl = new CheckoutController();
System.out.println(ctl.onPayClicked(small, new Customer(100)));
System.out.println(ctl.onPayClicked(big, new Customer(450)));
System.out.println(ctl.onPayClicked(big, new Customer(600)));
}
}
Output:
Paid Rs 75
Not enough balance for Rs 500
Paid Rs 500
Rs 35 of snacks pays Rs 40 delivery (Rs 75); Rs 500 gets free delivery.
Practice
1. Fix this line so it obeys the Law of Demeter: double fee = 500 * shop.getOwner().getAccount().getBank().getFeeRate();
Solution
class Bank { private final double feeRate; Bank(double r) { feeRate = r; } double feeRate() { return feeRate; } }
class Account { private final Bank bank; Account(Bank b) { bank = b; } double feeRate() { return bank.feeRate(); } }
class Owner { private final Account account; Owner(Account a) { account = a; } double feeRate() { return account.feeRate(); } }
class Shop {
private final Owner owner;
Shop(Owner o) { owner = o; }
double feeRate() { return owner.feeRate(); } // each class asks only its direct friend
}
public class Main {
public static void main(String[] args) {
Shop shop = new Shop(new Owner(new Account(new Bank(0.02))));
double fee = 500 * shop.feeRate(); // one dot: talk to the shop only
System.out.println("Fee on Rs 500: " + fee);
}
}
Fee on Rs 500: 10.0
Each class asks only its direct friend; if the bank's fee logic changes, only Bank changes.
2. Are these duplication? (a) MAX_LOGIN_ATTEMPTS = 3 and MAX_ITEMS_PER_ORDER = 3; (b) the same email-format regex in the signup form and the profile page.
Answer
(a) No: two different facts that happen to be equal. (b) Yes: one rule ("what is a valid email") in two places; give it one home, e.g. an Email value object.
3. Which GRASP principle decides who computes an order's total? Who should create OrderLine objects?
Answer
Information expert: the Order has the lines, so it computes the total. Creator: the Order contains its lines, so it creates them.
4. A method called isValid() also saves the object to the database. Which principle does it break?
Answer
The principle of least astonishment (and command-query separation): a question-shaped name shouldn't change state. Split it into isValid() and save().
Quick quiz
double fee = shop.getOwner().getAccount().getBank().getFeeRate();
Which principle does this break?
- A. DRY
- B. YAGNI
- C. Law of Demeter
- D. KISS
Answer
C. The checkout reaches through the owner, the account and the bank; if any of them changes, this line breaks. Ask the shop: shop.feeRate().
Interview questions
- What is DRY? Is all duplicated-looking code a DRY violation? One authoritative home for each piece of knowledge (Hunt & Thomas, 1999). No: duplication of knowledge is the problem; lines that look alike but change for different reasons can stay apart.
- What is KISS? Where does it come from? Prefer the simplest solution that works; associated with Kelly Johnson of Lockheed's Skunk Works.
- What is YAGNI and how does it relate to the open-closed principle? Don't build for imagined futures (XP, Ron Jeffries). OCP keeps the design easy to extend when the need is real; YAGNI says don't add extension points nobody needs yet.
- State the Law of Demeter. A method may call methods only on itself, its parameters, objects it creates and its own fields; not on objects returned by those. Also called the principle of least knowledge.
- Is
list.stream().filter(...).map(...)a Demeter violation? No: each call returns the same kind of object (a stream); it's a fluent API, not reaching into strangers. - What does GRASP stand for? Name its nine principles. General Responsibility Assignment Software Patterns (Craig Larman): information expert, creator, controller, low coupling, high cohesion, polymorphism, pure fabrication, indirection, protected variations.
- What is a pure fabrication? Give an example. A class that doesn't represent a domain concept, invented to keep coupling low and cohesion high: a repository, a
Taxcalculator, aReceiptPrinter. - What is a GRASP controller? How is it different from an MVC controller? The first non-UI object that receives a system event and delegates; MVC controllers are one common implementation of the idea.
- What is the principle of least astonishment? Code should behave the way most readers expect from its name and context; e.g. getters shouldn't change state.
- Can principles conflict? Yes: DRY can increase coupling if two places are forced to share code that changes for different reasons; KISS can argue against an extra interface that DIP suggests. Judge by what is likely to change.
Glossary
| Term | Meaning, with an example |
|---|---|
| DRY | Don't repeat yourself: one home for each piece of knowledge. One Tax class |
| WET | Jokey name for code that repeats knowledge: "write everything twice" |
| Knowledge (in DRY) | A fact or rule of the system: the tax rate, a validation rule |
| KISS | Keep it simple, stupid: the most boring solution that works |
| Ternary operator | cond ? a : b: value a if the condition is true, else b |
| Nested ternary | A ternary inside a ternary; hard to read |
| Skunk Works | Lockheed's advanced-projects team, led by Kelly Johnson |
| YAGNI | You aren't gonna need it: build features when needed, not when foreseen |
| Extreme programming (XP) | A development style of short steps, constant testing and frequent releases |
| Law of Demeter | A method talks only to itself, its parameters, objects it creates and its fields |
| Principle of least knowledge | Another name for the Law of Demeter |
| Train wreck | A chain of calls through other objects: a.getB().getC().doIt() |
| Tell, don't ask | Ask an object to do the job instead of pulling its data out (episode 6) |
| Fluent API | Methods that return the same kind of object so calls can be chained: streams, builders |
| Responsibility | Something a class must know or do |
| GRASP | General Responsibility Assignment Software Patterns: Larman's nine principles |
| Information expert | Give a job to the class that has the information for it. Cart.total() |
| Creator | B creates A if B contains A or has its initializing data. Cart.add creates CartItem |
| Controller (GRASP) | First object behind the UI that receives an event and delegates. CheckoutController |
| Low coupling | Few, loose dependencies between classes |
| High cohesion | A class's responsibilities belong together |
| Polymorphism (GRASP) | Let each type implement type-specific behaviour instead of if/switch on type |
| Protected variations | Wrap the parts likely to change behind a stable interface |
| Indirection | A middleman between two classes so they don't depend on each other directly |
| Pure fabrication | A made-up class (not a real-world concept) that keeps the design clean. Tax, a repository |
| Principle of least astonishment | Code behaves the way most readers expect. A getter only reads |
| Side effect | A change a method makes besides returning a value: clearing a list |
| Command-query separation | A method either changes state (command) or answers a question (query), not both (episode 51) |
Summary
- DRY: one home for every piece of knowledge, but don't merge things that only look alike.
- KISS: the boring, readable solution beats the clever one.
- YAGNI: build it when you need it, and keep the code easy to change.
- Law of Demeter: talk only to your direct friends; tell, don't ask.
- GRASP: information expert, creator, controller, low coupling, high cohesion, polymorphism, protected variations, indirection, pure fabrication.
- Least astonishment: names are promises.
Next episode: UML 1: class diagrams you actually need.