Patterns & principles · 9 of 10 · 13 min read
DRY, KISS and YAGNI
Three principles that pull against each other, what each one actually asks for, and when following one is the wrong call.
- Principles
- Good practice
Three rules of thumb that every developer can recite and that regularly get applied wrongly. The interesting part of each is not the expansion — it is the case where following it makes the code worse.
DRY — don’t repeat yourself
The original wording is the useful one: every piece of knowledge must have a single, unambiguous, authoritative representation within a system. Knowledge, not code. Two pieces of code that happen to look alike are not a DRY violation.
const MS_PER_DAY = 24 * 60 * 60 * 1000; // one definition of one fact
function daysBetween(a, b) {
return Math.round((b - a) / MS_PER_DAY);
}
function isStale(date) {
return Date.now() - date > 30 * MS_PER_DAY;
}
The same number typed in four places is four things to find when it changes, and the one you miss is the bug. That is the real cost DRY is about: not typing, but drift.
Where it is the wrong call
Two functions that look identical today but answer to different owners:
// Validation for a sign-up form
function validateSignup(user) {
if (!user.email.includes('@')) return 'invalid email';
if (user.password.length < 8) return 'password too short';
return null;
}
// Validation for an admin-created account — identical, today
function validateAdminCreate(user) {
if (!user.email.includes('@')) return 'invalid email';
if (user.password.length < 8) return 'password too short';
return null;
}
Merging them feels obvious. Then the rules diverge — admins get a 16-character minimum, sign-ups get a password-strength meter — and the shared function grows a flag:
// what "DRY" turned into, three requirements later
function validate(user, { isAdmin = false, skipStrength = false, allowPlusAddressing = true } = {}) {
// four branches nobody can read, serving two callers that no longer agree
}
A parameter that exists only to pick which caller you are is the signal that the abstraction was wrong. The duplication was cheaper.
The question to ask is not “do these look the same?” but “when this changes, must the other one change too?” If yes, it is one piece of knowledge — extract it. If no, it is a coincidence — leave it alone.
| Looks duplicated | Really is | Do |
|---|---|---|
| A tax rate in three files | one fact | extract a constant |
The same fetch + error handling everywhere |
one policy | extract a helper |
| Two validators that happen to match | two rules | leave them |
| Test setup repeated across tests | often clarity | leave it |
Test code is the common exception: a test that reads top to bottom with its data in front of you beats one that shares a fixture you have to go and find.
KISS — keep it simple
Simple means easy for the next person to understand, which is not the same as short. These two do the same thing:
// "Clever": fewer characters, more thinking
const group = (xs, k) => xs.reduce((a, x) => ((a[x[k]] ??= []).push(x), a), {});
// Simple: more characters, no thinking
function groupBy(items, key) {
const groups = {};
for (const item of items) {
const value = item[key];
groups[value] ??= [];
groups[value].push(item);
}
return groups;
}
console.log(groupBy([{ t: 'a' }, { t: 'b' }, { t: 'a' }], 't'));
// { a: [{t:'a'}, {t:'a'}], b: [{t:'b'}] }
The first uses the comma operator to sneak a return value out of a reduce. It is shorter and it
will cost somebody fifteen minutes one day.
Where simplicity actually comes from, in order of impact:
// 1. Guard clauses instead of nesting
function priceBad(user, item) {
if (user) {
if (user.active) {
if (item.inStock) {
return item.price * (user.isMember ? 0.9 : 1);
}
}
}
return null;
}
function price(user, item) {
if (!user?.active) return null;
if (!item.inStock) return null;
return item.price * (user.isMember ? 0.9 : 1); // the happy path, unindented
}
// 2. Names that remove the need for a comment
const d = 86_400_000; // what is d?
const MS_PER_DAY = 86_400_000; // no comment needed
// 3. One job per function
console.log(price({ active: true, isMember: true }, { inStock: true, price: 100 })); // 90
KISS is also the argument against reaching for a pattern early: a registry, a factory and a plugin point for two cases is indirection with nothing at the other end.
YAGNI — you aren’t gonna need it
Do not build for a requirement you have been told about but have not got. The cost is not just the hour of writing it:
// The requirement: export orders as CSV.
// What gets built "because we will need the others later":
const exporters = {
csv: (rows) => rows.map((r) => Object.values(r).join(',')).join('\n'),
json: (rows) => JSON.stringify(rows), // nobody has asked for this
xml: (rows) => `<rows>${rows.length}</rows>`, // nor this
pdf: () => { throw new Error('not implemented'); }, // and this is a lie in the registry
};
Four formats to test, document and keep compiling, three of which have never run against real data. When XML is finally requested the spec will be different from the guess, and the guess will have to be unpicked first — which is slower than starting from nothing.
What you pay for unused code:
- it is tested, reviewed and maintained like real code,
- it constrains the design, because the abstraction was shaped around imagined needs,
- it is wrong, because requirements arrive different from the prediction,
- and it still has to be removed.
What YAGNI is not
It is not an argument against design. Decisions that are expensive to reverse later — a boundary between modules, a data model, an error contract — are worth thinking about now. What it rules out is implementing functionality nobody has asked for.
// YAGNI does not say "do not define a boundary":
export function createOrderRepository({ http }) { /* one implementation, today */ }
// It says "do not write the three implementations you imagine you might want".
They pull against each other
That is the point, and it is what an interview is listening for.
| Pull | Pulls towards | Pulls against |
|---|---|---|
| DRY | extracting the shared thing | KISS: the abstraction can be harder than the copy |
| KISS | the obvious, repetitive version | DRY: obvious often means repeated |
| YAGNI | the smallest thing that works now | DRY: today there is only one caller |
A workable ordering: YAGNI first — do not build it at all. Then KISS — build the obvious version. Then DRY, once duplication has actually appeared and you can see what varies.
The “rule of three” encodes that: copy it the second time, and extract on the third, when you have three real examples and the right abstraction is visible rather than guessed.
// first time: write it
// second time: copy it, and notice
// third time: now you can see what varies, so extract that
Common mistakes
Extracting on the second occurrence
Mistake. Two similar blocks appear, so a shared helper is written immediately. Why it fails. With two examples you cannot tell which parts vary, so the abstraction is shaped by a guess — and a wrong abstraction is harder to remove than the duplication was. What to do instead. Wait for the third, or for a change that must apply to both.
Reading KISS as “fewer lines”
Mistake. Collapsing a readable loop into a dense one-liner. Why it fails. Simplicity is measured in the reader’s effort. A nested ternary chain is shorter and strictly harder. What to do instead. Optimise for the next person reading it at 2am, which is often you.
Using YAGNI to skip the boundary
Mistake. Putting fetch calls straight into components because the repository is “extra
layers”.
Why it fails. YAGNI is about unbuilt features, not about structure. Retrofitting a boundary
across thirty call sites is the expensive version of this decision.
What to do instead. One implementation behind a seam you can substitute. That is not
speculation; it is the cheap option in both directions.
Check yourself
3 questions from the bank on what you just read. Answering here does not affect your quiz history.
DRY says do not repeat yourself. When is extracting the duplication the wrong call?
What does the KISS principle ask of you?
What does YAGNI warn against?
Further reading
Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.
Reaching the end of a lecture marks it as read.