AlgoViz

YAGNI

easy 40 min

You 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

0:00 / 4:35

YAGNI

1:04Reel

More reels

One idea each, a minute or less.

Play all in Bytesized Learning

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

  1. 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.

  2. 1998

    Ron Jeffries publishes You're NOT gonna need it! on 4 April, as one of the XP practices.

  3. 1999

    Kent Beck's Extreme Programming Explained appears in October.

  4. 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.

  5. 2001

    The principles behind the Agile Manifesto call simplicity the art of maximizing the amount of work not done.

  6. 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.

Step 1 of 4

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.

One night in the hills
1 nightsunny

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.

Java
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); }}
Before. One of six methods is used, so five of six (83 percent) were built on a guess. All six must be read, compiled, tested and kept working.

Built for guesses

SignUpPage+ submit()

1/4The need

A page that saves a member.

usesimplements

Built for the need

SignUpPage+ submit()MemberService- db: Database+ save(m)Database+ save(m)

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 guessedIt comes differentlyIt never comes
Built nowBuild, delay, carry until thenBuild, delay, carry, repairBuild, delay, carry for ever
Built laterBuildBuildNothing
Building now wins only if later is much more expensive than now. Good code keeps that difference small.

Wait if

p⋅L<N+Cp \cdot L < N + C
p is the chance that the need comes, L the cost later, N the cost now, C the cost of carry until then. With N = 5 days, L = 8 days, C = 3 days: waiting costs 8p on average, building now costs 8 for sure. Waiting is better for every p below 1. The numbers are an example.

Examples

Three more guesses

Python
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())   # 3300
A cart. The first one was ready for currencies, discounts, tax, gift wrap and wish lists. The second one does what the shop does today.
Edit and run it in your browser

Look 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.

TypeScript
// 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);
A button factory with themes, languages, analytics and experiments, and the button that was needed. Translation is added when the product goes to a second country.
C++
#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"; }
A service with interfaces for logger, cache and metrics was cut to its work. The cache came back when a profile showed that the same result was computed again and again.

The limit

What is not a guess

Not covered by YAGNIWhySmallest form on the first day
SecurityAn attack does not wait for a ticketCheck rights, hash passwords, no secrets in code
Error handlingNetworks and people will failOne clear message, no half-done state
LoggingYou will have to find out what happenedOne line per important event
Tests and clean namesThey make later cheapTests for the core
Backups, historyLost data cannot be added laterKeep the raw event and its time
Public contracts, idsOthers build on themA version in the address, ids without meaning
Hard choices of structureExpensive to turn aroundThink and note the reason. Still build little
The last row is a nuance. Core architecture deserves early thought because it is hard to change. It does not deserve early features.

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.99 in 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), with plus and show. 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 guess would have used commas and had an XML twin.

The life of an idea

A list of ideas is cheap. A list costs no tests.

Neighbours

How it fits with other principles

PrincipleRelation
KISSKISS is about the form of what you build, YAGNI about whether and when
Open/closedAn extension point is a feature. It needs a reason: a second or third example, or outsiders
DRYDo not extract a shared framework for a user who may come
SOLIDSmall parts with one reason make later cheap, so they serve YAGNI
Unit testingWithout 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