Patterns are named solutions; principles are the rules of thumb that tell you whether a piece of code is heading somewhere good. Four of them come up in almost every code review: DRY (keep each piece of knowledge in one place), KISS (prefer the simplest design that works), YAGNI (do not build what nobody needs yet) and the Law of Demeter (an object talks only to its direct collaborators). All four push toward the same goal, code that is cheap to change, by lowering coupling and raising cohesion. Each one also has a failure mode when applied blindly, so this lesson covers both.
Think of it like
The cashier and your wallet
At a till, the cashier tells you the total and you pay. The cashier does not reach into your pocket, open your wallet, count your notes and take the right ones. If you switch from cash to a phone, the shop changes nothing, because it only ever talked to you. That is the Law of Demeter. The same shop keeps one price list instead of a price sticker that disagrees with the till (DRY), uses a plain till instead of a custom robot (KISS), and does not install a second till for the crowds it might get one day (YAGNI).
Four rules of thumb
| Principle | In one sentence | Comes from |
|---|---|---|
| DRY | Every piece of knowledge has one authoritative home. | The Pragmatic Programmer (Andy Hunt and Dave Thomas, 1999) |
| KISS | Choose the simplest design that solves today's problem. | An engineering slogan (its exact origin is debated) |
| YAGNI | Do not build a capability until it is actually needed. | Extreme Programming (late 1990s) |
| Law of Demeter | A method talks to its friends, not to strangers. | The Demeter project, Northeastern University, 1987 |
DRY: don't repeat yourself
The Pragmatic Programmer states DRY as: "Every piece of knowledge must have a single, unambiguous, authoritative representation within a system." The key word is knowledge. DRY is not a rule against similar-looking lines; it is a rule against one business fact (a tax rate, a validation rule, a file format) living in several places that can drift apart.
// Before
// cart.ts
function cartShipping(total: number): number {
return total >= 50 ? 0 : 5;
}
// invoice.ts (written later, by someone else)
function invoiceShipping(total: number): number {
return total > 50 ? 0 : 4.99; // already disagrees with the cart
}
// After
// shipping.ts: cart.ts and invoice.ts both call shippingFor()
export const FREE_SHIPPING_FROM = 50;
export const FLAT_SHIPPING = 5;
export function shippingFor(total: number): number {
return total >= FREE_SHIPPING_FROM ? 0 : FLAT_SHIPPING;
}Real duplication
- The same rule appears twice and must change together
- Example: the password policy checked in the sign-up form and again in the API
- Example: a list of order states hard-coded in three
switchstatements - Can look different on the surface (a regex here, a loop there)
Coincidental similarity
- Two pieces of code happen to look alike today
- Example:
maxRetries = 3andmaxLoginAttempts = 3 - Each will change for its own reasons
- Merging them couples two things that are not related
The rule of three. A common heuristic is to tolerate the second copy and extract on the third. With two examples you often cannot tell which parts are the shared rule and which are coincidence; with three, the real abstraction is usually visible.
// Before: one "reusable" function, bent by every caller
function label(u: User, forInvoice: boolean, short: boolean) {
if (forInvoice) return `${u.last.toUpperCase()}, ${u.first}`;
return short ? u.first : `${u.first} ${u.last}`;
}
// After: separate functions, each with one reason to change
const invoiceName = (u: User) => `${u.last.toUpperCase()}, ${u.first}`;
const greetingName = (u: User) => u.first;
const fullName = (u: User) => `${u.first} ${u.last}`;KISS: keep it simple
KISS ("keep it simple, stupid", often softened to "keep it short and simple") asks for the design with the fewest moving parts that solves the actual problem. Simple code is easier to read, test and debug, and when it turns out to be wrong it is cheaper to replace. Rich Hickey's talk Simple Made Easy (2011) draws the line that matters here: simple means not interleaved, easy means near at hand. KISS asks for simple.
Simple
- Few concepts, not tangled together
- A property of the code itself
- Example: a plain function with early returns
- Stays easy for the next reader
Easy
- Familiar or quick to type for you, right now
- A property of your experience
- Example: a clever one-liner, or adding a framework you already know
- Can hide a lot of complexity behind one call
// Before: clever, compact, and hard to check
const fee = (kg: number, express: boolean) =>
kg <= 0 ? 0 : express ? (kg > 10 ? 30 : 15) : kg > 10 ? 12 : 6;
// After: one rule per line
function fee(kg: number, express: boolean): number {
if (kg <= 0) return 0;
const heavy = kg > 10;
if (express) return heavy ? 30 : 15;
return heavy ? 12 : 6;
}YAGNI: you aren't gonna need it
YAGNI comes from Extreme Programming: implement a capability when you actually need it, not when you foresee that you might. The prediction is often wrong, and even when it is right, the version built in advance usually does not fit the need that finally arrives. The code smell it prevents is speculative generality: hooks, parameters, abstract base classes and plugin points that exist "in case" but have one user or none. Building them has a cost, and so does keeping them.
- Cost of building: time spent on the unused feature instead of one that is needed now.
- Cost of delay: the needed feature ships later.
- Cost of carrying: every reader, test and refactoring has to work around the extra code, for as long as it exists.
- Cost of being wrong: when the real requirement arrives and differs, the speculative code must be reworked or removed first.
// Before
interface ExportFormat {
name: string;
render(rows: string[][]): string;
}
class FormatRegistry {
private formats = new Map<string, ExportFormat>();
register(f: ExportFormat) { this.formats.set(f.name, f); }
get(name: string) { return this.formats.get(name); }
}
// ...and a CsvFormat class, the only format anyone uses
// After
function toCsv(rows: string[][]): string {
return rows.map((r) => r.join(",")).join("\n");
}
// When a second format is really requested, extract an
// interface then, shaped by two real examples.The Law of Demeter
The Law of Demeter, also called the principle of least knowledge, was formulated in 1987 at Northeastern University, in a research project named Demeter. Informally: talk to your friends, not to strangers. Formally, a method m of an object O should only call methods of:
- 1
Oitself (this.helper()). - 2
m's parameters (order.pay()whenorderwas passed in). - 3Objects that
mcreates (new Receipt(...).print()). - 4
O's direct fields, its components (this.wallet.debit()).
class Checkout {
pay(order: Order, amount: number) {
// order is a friend; the customer and the wallet are not
return order.customer().wallet().debit(amount);
}
}Anything returned by a call to one of those four is a stranger, and calling a method on it means knowing about an object you were never given. A chain of such calls looks like a line of coupled train cars, hence the name train wreck. Checkout now depends on Order, Customer and Wallet, and on the fact that an order has one customer who pays from one wallet. Every service that copies the chain makes the same structure harder to change.
class Checkout {
pay(order: Order, amount: number) {
return order.pay(amount);
}
}
class Order {
constructor(private customer: Customer) {}
pay(amount: number) {
return this.customer.pay(amount);
}
}
class Customer {
constructor(private wallet: Wallet) {}
pay(amount: number) {
return this.wallet.debit(amount);
}
}Instead of asking for an object's internals and acting on them, the caller tells its friend what it wants done. Each class makes one hop to its own field, and the knowledge of how a customer pays lives in Customer alone. This is encapsulation (see The Four Pillars of OOP) applied to collaborators rather than to fields, and it is delegation, the same mechanism that Composition vs Inheritance relies on.
What the visualizer shows
The visualizer at the top of the page runs both designs for real. The client creates a Wallet with 50, the customer ana, her order, and two services: Checkout takes a payment of 30 and Refunds sends back 10, so the wallet ends at 30 in every version. Switch between Before and With Demeter, press Play or step with the arrow keys, and watch the sequence view.
- 1
Before: the services reach in
checkout.pay(order, 30)callsorder.customer(), getsanaback, callsana.wallet(), getswalletback, and then callswallet.debit(30)itself. In the sequence view,checkout's arrows go to three lifelines. - 2
Before: strangers in the class diagram
Dashed dependency arrows run from both
CheckoutandRefundstoOrder,CustomerandWallet. Whencheckoutdebits the wallet, theCheckouttoWalletdependency lights up: a direct link to an object it was never given. - 3
With Demeter: one hop each
checkoutcallsorder.pay(30),ordercallsana.pay(30)through itsbuyerfield, andanacallswallet.debit(30)through herwalletfield. The arrows form a staircase: every message goes to a neighbor. - 4
The same result
In both versions the payment returns 20 and the refund returns 30, the wallet's new balance, and both runs have the same length (26 on the step counter). Demeter changes who knows what, not what happens.
- 5
Apply the change request
Press Use bank accounts: wallets are replaced by a
BankAccountwithwithdrawanddeposit. Toggle Before and With Demeter to compare the badges and the panel.
| Change request: wallet becomes a bank account | Before (train wreck) | With Demeter |
|---|---|---|
| Existing classes edited | 3 (Customer, Checkout, Refunds) | 1 (Customer) |
| New classes | 1 (BankAccount) | 1 (BankAccount) |
| Lines changed in existing classes | 10 | 6 |
| Classes touched (edited, new, removed) | 5 | 3 |
Wallet and add BankAccount; the difference is who else had to be opened. With two services the gap is two classes; in a real codebase every report, job and endpoint that copied the chain is one more edit, while the Demeter change stays in Customer however many callers there are.Coupling and cohesion
- Coupling
- How much one module depends on another: how many of its classes, methods and internal details it knows about. Low coupling means a change in one place rarely forces changes elsewhere.
- Cohesion
- How closely the parts of one module belong together: whether its fields and methods serve one purpose. High cohesion means a change in one concept is made in one place.
| Principle | Effect on coupling | Effect on cohesion |
|---|---|---|
| DRY | Adds a dependency on the shared home (wanted when the knowledge is truly shared) | Raises it: each rule lives in the module that owns it |
| KISS | Lowers it: fewer parts means fewer connections | Neutral to positive: less incidental code mixed into a module |
| YAGNI | Lowers it: no hooks and extension points for imaginary clients | Raises it: modules contain only what their purpose needs |
| Law of Demeter | Lowers it: callers depend on their direct collaborators only | Raises it: behavior moves into the class that owns the data |
When the principles conflict
DRY vs decoupling
- Sharing code between two services or teams couples their release cycles
- A shared library of "common models" can force everyone to upgrade together
- Across boundaries, a little duplication is often the cheaper option
- Inside one module, prefer DRY
YAGNI vs extensibility
- Inside your own code, add the extension point when the second case arrives
- Public APIs, wire protocols and stored formats are expensive to change later
- There, a small amount of foresight (a version field, an options object) is cheap insurance
Demeter vs KISS
- Each tell-don't-ask step adds a small forwarding method
- For a stable structure that rarely changes, a short chain can be the simpler code
- Where the inner objects are likely to change, the extra methods pay for themselves
- 1
Ask what will change
Principles are about the cost of change. Identify which part of the design is likely to change, and which callers would feel it.
- 2
Weigh how hard it is to undo
Internal code can be refactored later, so lean on YAGNI and KISS. Public contracts and data formats cannot, so invest a little more up front.
- 3
Check the boundary
Within a module, remove duplication and reach-through. Across teams or services, prefer copies and narrow interfaces over shared internals.
- 4
Prefer the version that is easy to change
When two principles disagree, pick the design that the next change will be cheapest to make in. That is the purpose all four serve.
Summary
| Principle | Smell it prevents | How to spot it | Overuse risk |
|---|---|---|---|
| DRY | Duplicated knowledge (shotgun surgery: one change, many edits) | A bug fix that must be repeated in several places | The wrong abstraction: one function full of flags for unrelated callers |
| KISS | Needless complexity | Code that needs a long explanation, or clever tricks a reviewer must decode | Oversimplifying: ignoring real edge cases or real requirements |
| YAGNI | Speculative generality | Interfaces with one implementation, unused parameters, "for later" hooks | Painting yourself into a corner on hard-to-change decisions |
| Law of Demeter | Train wrecks and inappropriate intimacy | a.b().c().d() chains through objects with behavior | Middle-man classes full of one-line forwarding methods |
Implementation
The With Demeter version of the visualizer as a complete program: a Wallet, a Customer that pays from it, an Order that tells its customer to pay, and two services, Checkout and Refunds, that talk only to the order they are given. Each method calls only its own fields or parameters. Replacing the wallet with a bank account would change only Customer. In C++ the objects refer to their collaborators by reference, and all of them live in main.
class Wallet:
def __init__(self, balance: int) -> None:
self._balance = balance
def debit(self, amount: int) -> int:
if amount > self._balance:
raise ValueError("insufficient funds")
self._balance -= amount
return self._balance
def credit(self, amount: int) -> int:
self._balance += amount
return self._balance
class Customer:
"""The only class that knows how a customer holds money."""
def __init__(self, wallet: Wallet) -> None:
self._wallet = wallet
def pay(self, amount: int) -> int:
return self._wallet.debit(amount) # a direct field
def refund(self, amount: int) -> int:
return self._wallet.credit(amount)
class Order:
def __init__(self, customer: Customer) -> None:
self._customer = customer
def pay(self, amount: int) -> int:
return self._customer.pay(amount) # tell, don't ask
def refund(self, amount: int) -> int:
return self._customer.refund(amount)
class Checkout:
def pay(self, order: Order, amount: int) -> int:
return order.pay(amount) # a parameter: a friend
class Refunds:
def send(self, order: Order, amount: int) -> int:
return order.refund(amount)
wallet = Wallet(50)
ana = Customer(wallet)
order = Order(ana)
checkout = Checkout()
refunds = Refunds()
print(checkout.pay(order, 30)) # 20
print(refunds.send(order, 10)) # 30Key takeaways
- DRY is about knowledge, not text: each business rule should have one authoritative home, while code that only looks alike may stay separate. Wait for the third copy before extracting.
- KISS asks for simple (few, untangled concepts), not easy (familiar or short). A readable
ifbeats a clever one-liner. - YAGNI: build a capability when it is needed, not when it is predicted. Speculative code costs time to build, delays real work, and must be carried and reworked.
- The Law of Demeter lets a method call only itself, its parameters, objects it creates and its direct fields. Replace train wrecks with tell, don't ask.
- In the visualizer's change request (wallet becomes a bank account), the train-wreck version edits 3 existing classes and the Demeter version edits 1, because only
Customerknew about the wallet. - All four principles aim at low coupling and high cohesion. When they conflict, choose the design whose next change is cheapest, and invest more foresight only where decisions are hard to undo.
Common pitfalls
- Merging code that merely looks the same. Two rules that change for different reasons end up in one function with flags, and every change to it risks breaking an unrelated caller.
- Treating YAGNI as permission to skip tests, refactoring or clear names. It applies to features you might need, not to the quality that keeps future features cheap.
- Counting dots instead of applying the Law of Demeter. Builder chains, stream pipelines and reads from plain data objects are not violations; reaching through objects with behavior is.
- Fixing every train wreck with a forwarding method on the nearest class. When a class fills up with one-line delegations, move the behavior to where the data lives instead.
- Confusing simple with easy: adding a familiar framework, a generic engine or a clever trick because it was quick to write, and leaving the next reader with more concepts to learn.
Interview tips
- In LLD rounds, say out loud when you avoid a chain such as
parkingLot.getFloor(2).getSpot(7).park(car)and give the floor or lot a method instead. Naming the Law of Demeter and the coupling it saves is a strong signal. - Define DRY with the word knowledge, and pair it with the risk of the wrong abstraction. Interviewers like candidates who know when not to apply a principle.
- When asked to make a design "extensible", apply YAGNI explicitly: build the extension point where a second variant is known or the decision is hard to reverse, and say what you are deliberately leaving out.
Real-world applications
- Configuration and constants: tax rates, limits and feature flags kept in one module that every caller reads (DRY).
- Code review checklists: reviewers flag duplicated rules, clever code that needs a comment to decode, unused parameters and hooks, and long call chains.
- Domain models: orders, accounts and carts that expose operations (
order.pay(),cart.addItem()) instead of their internal object graph (Law of Demeter). - Microservice boundaries: teams accept some duplicated models rather than a shared library that couples their deployments (DRY weighed against decoupling).
- Startups and prototypes: shipping the simplest working version first and adding abstractions once real usage shows where variation is (KISS and YAGNI).
Test yourself
Which of these is a violation of the Law of Demeter?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.