YAGNI
easy 40 minYou aren't gonna need it: build a feature when somebody needs it, and not when you imagine that somebody will.
Video lesson · Chapter 1 of 6
Make a prediction
YAGNI
1:04Reel
More reels
One idea each, a minute or less.
KISS or YAGNI?
0:31Reel
Theory
Read or listen first. About 2 min.
What it is
YAGNI stands for you aren't gonna need it. It comes from Extreme Programming. Ron Jeffries put it like this in 1998: always implement things when you actually need them, never when you just foresee that you need them.
It is about presumptive features: code for a wish that nobody has yet. A second database, an export that was not asked for, a plugin system for one plugin. It is also about the hooks and parameters that are put in for such a wish.
YAGNI is not against clean code, tests or refactoring. These are what make it work. Martin Fowler says it clearly: yagni applies to features, and not to effort that makes the software easier to change. If change is expensive in your code, YAGNI turns into a trap.
Why it exists
Guesses are often wrong. Then the work is lost. But even a right guess costs: something else was not built in that time, and everybody has to work around the new code until it is used.
Fowler names four costs. Build: the work itself. Delay: what you did not deliver in the meantime. Carry: each later change is harder because of the extra code. Repair: the feature was built before the need was understood, and must be changed.
And waiting brings information. When a member asks for an export, they show you the columns. Before that you can only invent them.
A short history
1974
Donald Knuth warns that premature optimization is the root of all evil, and adds that the critical 3 percent should not be passed up. It is a relative of YAGNI about speed.
1998
Ron Jeffries publishes You're NOT gonna need it! on 4 April, as one of the XP practices.
1999
Kent Beck's Extreme Programming Explained appears in October.
2000
Martin Fowler's keynote for XP 2000, Is Design Dead?, asks whether evolving design can replace planned design, and names the practices that make it possible: tests, integration and refactoring.
2001
The principles behind the Agile Manifesto call simplicity the art of maximizing the amount of work not done.
2015
Fowler's article Yagni (26 May) describes the costs of build, delay, carry and repair.
Words to know
- Presumptive feature
- Code for a feature that is not yet made available for use.
- Speculative generality
- Hooks, parameters and layers for a future that is only imagined.
- Cost of delay
- The value of what you could have delivered instead.
- Cost of carry
- The extra effort for all work around code that is not used.
- Cost of repair
- Changing a feature that was built on a wrong guess.
- MVP
- Minimum viable product: the smallest thing that real users can judge.
- One-way door
- A decision that is hard to take back, such as a published API.
- Two-way door
- A decision that can be changed cheaply, such as a private class.
- Parallel change
- Expand, migrate, contract: a safe way to change a shape that is in use.
- Dead code
- Code that no path in use reaches.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
How it works
Step through the idea, or press Play.
Is it needed now?. By whom, and how do we know?
Understand it
Start here
A tent for every weather
Lee and Max go camping for one night. The forecast is sunny. Max wants to be safe against everything.
Frames 2 to 5 show the four costs. Frame 6 is YAGNI done well, and frame 7 is its limit.
The smell
Six methods, one user
The task was: save a member. Read what else arrived.
class MemberService { private DbStrategy db; // What if somebody needs XML one day? String exportToXml(Member m) { /* 25 lines */ return ""; } // What if CSV? String exportToCsv(Member m) { /* 20 lines */ return ""; } // What if JSON? String exportToJson(Member m) { /* 20 lines */ return ""; } // What if PDF reports? byte[] pdfReport(Member m) { /* 60 lines */ return new byte[0]; } // What if we change the database? void setDbStrategy(DbStrategy s) { db = s; } // The only thing that was asked for: void save(Member m) { db.save(m); }}Built for guesses
1/4The need
A page that saves a member.
usesimplements
Built for the need
1/3First version
One path, and each part has a caller.
uses
Asks
- What do we need today?
- Is it in the requirements?
- Can it be added later?
- What is the simplest thing that works?
Says
- What if we need several tenants?
- Let us add plugins, just in case
- We might need this export
- Let us make it ready for any scale
The costs
What unused code costs
Build
Time for a feature that nobody uses yet.
Delay
The thing that people asked for comes later.
Carry
It must be read, tested, updated, secured and moved along with every change.
Repair
When the need comes it looks different. Old users of the wrong shape are in the way.
Guess now or build later
| The need comes as guessed | It comes differently | It never comes | |
|---|---|---|---|
| Built now | Build, delay, carry until then | Build, delay, carry, repair | Build, delay, carry for ever |
| Built later | Build | Build | Nothing |
Wait if
Examples
Three more guesses
class NoConverter: def convert(self, cents): return centsclass NoDiscount: def apply(self, cents): return centsclass NoTax: def add(self, cents): return centsclass ReadyForEverything: def __init__(self): self.items = [] self.currency, self.discount, self.tax = NoConverter(), NoDiscount(), NoTax() self.gift_wrap = self.wish_list = None def total(self): t = sum(cents for _, cents in self.items) return self.tax.add(self.currency.convert(self.discount.apply(t))) # in which order? nobody askedclass Cart: def __init__(self): self.items = [] def add(self, name, cents): self.items.append((name, cents)) def total(self): return sum(cents for _, cents in self.items)cart = Cart()cart.add("Map", 900)cart.add("Rope", 2400)print(cart.total()) # 3300Look at the long line. Is the discount taken before or after tax? Are euros discounted or dollars? The author had to choose without a customer to ask. The first real discount will probably need another order, so this code will be repaired before it is used for the first time.
// first version: a label and a clickfunction createButton(label: string, onClick: () => void): HTMLButtonElement { const b = document.createElement("button"); b.textContent = label; b.onclick = onClick; return b;}// a year later, the second language is realconst words: Record<string, string> = { save: "Speichern" };const createTranslated = (key: string, onClick: () => void) => createButton(words[key] ?? key, onClick);#include <iostream>#include <optional>#include <string>class Report { // first version: only the workpublic: std::string make() const { return "result"; }};class CachedReport { // later, because a measurement asked for it Report report_; std::optional<std::string> saved_;public: const std::string& make() { if (!saved_) saved_ = report_.make(); return *saved_; } void invalidate() { saved_.reset(); } // the real need also showed when it must be thrown away};int main() { CachedReport r; std::cout << r.make() << r.make() << "\n"; }The limit
What is not a guess
| Not covered by YAGNI | Why | Smallest form on the first day |
|---|---|---|
| Security | An attack does not wait for a ticket | Check rights, hash passwords, no secrets in code |
| Error handling | Networks and people will fail | One clear message, no half-done state |
| Logging | You will have to find out what happened | One line per important event |
| Tests and clean names | They make later cheap | Tests for the core |
| Backups, history | Lost data cannot be added later | Keep the raw event and its time |
| Public contracts, ids | Others build on them | A version in the address, ids without meaning |
| Hard choices of structure | Expensive to turn around | Think and note the reason. Still build little |
Build it now?
You store prices. Today there is one currency. What do you do about others?
BreaksA currency service with daily rates
- How
- Converter, rates, rounding rules per country.
- Limit
- Nobody sells abroad. The rules are guesses.
- Choose when
- A second country has signed.
WorksA plain float called price
- How
price = 9.99in forty places.- Limit
- Cheap now. Later every place must be found, and floats lose cents today already.
- Choose when
- A sketch.
StrongWhole cents, in one small type
- How
Money(cents), withplusandshow. No currency yet.- Limit
- One class. It is needed today for the rounding.
- Choose when
- Today's need also gives tomorrow one place to change.
How it works
From wish to feature
Asking before building
The life of an idea
Neighbours
How it fits with other principles
| Principle | Relation |
|---|---|
| KISS | KISS is about the form of what you build, YAGNI about whether and when |
| Open/closed | An extension point is a feature. It needs a reason: a second or third example, or outsiders |
| DRY | Do not extract a shared framework for a user who may come |
| SOLID | Small parts with one reason make later cheap, so they serve YAGNI |
| Unit testing | Without tests nobody dares to change, and people build early out of fear |
Summary
The whole topic in one minute.
Build what is needed now. A guess costs when it is wrong, and it also costs when it is right: build, delay, carry, repair.
YAGNI works only if later is cheap. So tests, clear names and small parts are never optional.
Ask one more question: can this be added later? Security, error handling, data that is lost, public contracts and ids are hard or impossible to add, so think about them early.
- Implement when needed, not when foreseen.
- A right guess costs too: build, delay, carry.
- Clean code and tests are what makes waiting safe.
- Security, errors, lost data and public contracts are not guesses.
- For a one-way door look for the smallest step that keeps it open.
- Note ideas. Remove what is not used.
Sources
- Martin Fowler: Yagni (2015)
- Ron Jeffries: You're NOT gonna need it! (1998)
- Martin Fowler: Is Design Dead?
- Principles behind the Agile Manifesto
- Danilo Sato: Parallel Change (2014)
- PEP 3103: rejected switch statement
- Go 1.18 release
- Kubernetes deprecation policy
- Rust: Stability as a deliverable
- Semantic Versioning