YAGNI — You Aren't Gonna Need It
Introduction
A developer is asked to send an email whenever an order is placed. Thinking ahead, they also make room for text messages, phone notifications, Slack and webhooks: an interface for channels, a router that picks channels from a settings file, a queue and retries. Months later the shop still sends only emails. Every extra part is still in the code, and everyone who works on it has to read past it.
YAGNI stands for "you aren't gonna need it". Martin Fowler describes it as a mantra from Extreme Programming that agile teams now use widely, "a statement that some capability we presume our software needs in the future should not be built now". The phrase began in a conversation on a project called C3: Chet Hendrickson brought Kent Beck a series of capabilities the system would soon need, and to each one Beck replied, "you aren't going to need it". Ron Jeffries gave the rule its plainest form in 1998: "Always implement things when you actually need them, never when you just foresee that you need them."
The picture shows a small report built both ways, and what building ahead costs:

What a Feature Built Early Costs
Fowler calls code like that a presumptive feature: "any code that supports a feature that isn't yet being made available for use." He explains its cost with an example. A startup sells insurance for ships, and its software has two parts, one that prices a policy and one that sells it. The team is adding pricing for storm risks, and they know that in six months they will also need pricing for piracy risks. Building the piracy pricing now, while they are in the pricing code anyway, looks efficient. Fowler counts four costs that say otherwise.
The cost of build. The guess may be wrong. If pirates stop being a risk, nobody needs piracy pricing, and what is lost is "all the effort spent on analyzing, programming, and testing this now useless feature."
The cost of delay. Even if the guess is right, the time spent on piracy pricing was not spent on the sales software for storm insurance. In his example the storm insurance reaches customers, and starts earning, two months later than it could have.
The cost of carry. The extra code makes every other change slower, because "this complexity makes it harder to modify and debug that software, thus increasing the cost of other features." The team pays this on every feature it builds until the piracy pricing is finally used, or removed.
The cost of repair. Teams keep learning about their users and their code, so a feature written months before it is used is often not the way they would write it by then. It has to be reworked, or worked around.
The odds are against the early feature, too. Fowler puts the chance that it is not needed at two in three or worse, citing Kohavi and colleagues, who studied features built at Microsoft and found that "even with careful up-front analysis, only ⅓ of them improved the metrics they were designed to improve."
A Report Built for Formats Nobody Asked For
The requirement is small: the sales team wants a sales report as plain text, each product's revenue and then the total. Here it is built with room for formats nobody asked for: an interface for formatters, a text formatter, a CSV formatter, an Excel formatter, a registry that finds a formatter by its name, and a generator that asks the registry.
# A sales report built for formats nobody asked for: the requirement is one
# text report, and the design makes room for CSV and Excel as well.
from abc import ABC, abstractmethod
from dataclasses import dataclass
@dataclass(frozen=True)
class Sale:
product: str
cents: int
class ReportFormatter(ABC):
@abstractmethod
def format(self, sales: list[Sale]) -> str: ...
@abstractmethod
def file_extension(self) -> str: ...
# Whole cents as dollars and cents, the same in every locale
def dollars(cents: int) -> str:
return f"${cents // 100}.{cents % 100:02d}"
class TextFormatter(ReportFormatter):
def format(self, sales: list[Sale]) -> str:
lines = ["Sales Report", "-" * 24]
for sale in sales:
lines.append(f"{sale.product}: {dollars(sale.cents)}")
lines.append("-" * 24)
lines.append(f"Total: {dollars(sum(s.cents for s in sales))}")
return "\n".join(lines)
def file_extension(self) -> str:
return ".txt"
# Nobody asked for CSV.
class CsvFormatter(ReportFormatter):
def format(self, sales: list[Sale]) -> str:
rows = ["product,cents"] + [f"{s.product},{s.cents}" for s in sales]
return "\n".join(rows)
def file_extension(self) -> str:
return ".csv"
# Nobody asked for Excel either: a placeholder.
class ExcelFormatter(ReportFormatter):
def format(self, sales: list[Sale]) -> str:
raise NotImplementedError("Excel support coming soon")
def file_extension(self) -> str:
return ".xlsx"
class FormatterRegistry:
def __init__(self) -> None:
self._formatters: dict[str, ReportFormatter] = {}
def add(self, name: str, formatter: ReportFormatter) -> None:
self._formatters[name] = formatter
def get(self, name: str) -> ReportFormatter:
if name not in self._formatters:
raise ValueError(f"Unknown format: {name}")
return self._formatters[name]
class ReportGenerator:
def __init__(self, registry: FormatterRegistry, format_name: str) -> None:
self._formatter = registry.get(format_name)
def generate(self, sales: list[Sale]) -> str:
return self._formatter.format(sales)
def main() -> None:
registry = FormatterRegistry()
registry.add("text", TextFormatter())
registry.add("csv", CsvFormatter())
registry.add("excel", ExcelFormatter())
sales = [
Sale("Desk lamp", 1500000),
Sale("Office chair", 2350050),
Sale("Bookshelf", 875025),
]
generator = ReportGenerator(registry, "text")
print(generator.generate(sales))
if __name__ == "__main__":
main()import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
// A sales report built for formats nobody asked for: the requirement is one
// text report, and the design makes room for CSV and Excel as well.
record Sale(String product, int cents) {}
interface ReportFormatter {
String format(List<Sale> sales);
String fileExtension();
}
class TextFormatter implements ReportFormatter {
// Whole cents as dollars and cents, the same in every locale
static String dollars(int cents) {
int rest = cents % 100;
return "$" + cents / 100 + "." + (rest < 10 ? "0" : "") + rest;
}
public String format(List<Sale> sales) {
List<String> lines = new ArrayList<>(List.of("Sales Report", "-".repeat(24)));
int total = 0;
for (Sale sale : sales) {
lines.add(sale.product() + ": " + dollars(sale.cents()));
total += sale.cents();
}
lines.add("-".repeat(24));
lines.add("Total: " + dollars(total));
return String.join("\n", lines);
}
public String fileExtension() {
return ".txt";
}
}
// Nobody asked for CSV.
class CsvFormatter implements ReportFormatter {
public String format(List<Sale> sales) {
List<String> rows = new ArrayList<>(List.of("product,cents"));
for (Sale sale : sales) {
rows.add(sale.product() + "," + sale.cents());
}
return String.join("\n", rows);
}
public String fileExtension() {
return ".csv";
}
}
// Nobody asked for Excel either: a placeholder.
class ExcelFormatter implements ReportFormatter {
public String format(List<Sale> sales) {
throw new UnsupportedOperationException("Excel support coming soon");
}
public String fileExtension() {
return ".xlsx";
}
}
class FormatterRegistry {
private final Map<String, ReportFormatter> formatters = new HashMap<>();
void add(String name, ReportFormatter formatter) {
formatters.put(name, formatter);
}
ReportFormatter get(String name) {
ReportFormatter formatter = formatters.get(name);
if (formatter == null) {
throw new IllegalArgumentException("Unknown format: " + name);
}
return formatter;
}
}
class ReportGenerator {
private final ReportFormatter formatter;
ReportGenerator(FormatterRegistry registry, String formatName) {
this.formatter = registry.get(formatName);
}
String generate(List<Sale> sales) {
return formatter.format(sales);
}
}
public class ReportApp {
public static void main(String[] args) {
FormatterRegistry registry = new FormatterRegistry();
registry.add("text", new TextFormatter());
registry.add("csv", new CsvFormatter());
registry.add("excel", new ExcelFormatter());
List<Sale> sales = List.of(
new Sale("Desk lamp", 1500000),
new Sale("Office chair", 2350050),
new Sale("Bookshelf", 875025));
ReportGenerator generator = new ReportGenerator(registry, "text");
System.out.println(generator.generate(sales));
}
}#include <iostream>
#include <map>
#include <memory>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
// A sales report built for formats nobody asked for: the requirement is one
// text report, and the design makes room for CSV and Excel as well.
struct Sale {
std::string product;
int cents;
};
class ReportFormatter {
public:
virtual ~ReportFormatter() = default;
virtual std::string format(const std::vector<Sale>& sales) const = 0;
virtual std::string fileExtension() const = 0;
};
// Whole cents as dollars and cents, the same in every locale
std::string dollars(int cents) {
int rest = cents % 100;
return "$" + std::to_string(cents / 100) + "." + (rest < 10 ? "0" : "") +
std::to_string(rest);
}
class TextFormatter : public ReportFormatter {
public:
std::string format(const std::vector<Sale>& sales) const override {
std::string out = "Sales Report\n" + std::string(24, '-') + "\n";
int total = 0;
for (const Sale& sale : sales) {
out += sale.product + ": " + dollars(sale.cents) + "\n";
total += sale.cents;
}
out += std::string(24, '-') + "\n";
out += "Total: " + dollars(total);
return out;
}
std::string fileExtension() const override { return ".txt"; }
};
// Nobody asked for CSV.
class CsvFormatter : public ReportFormatter {
public:
std::string format(const std::vector<Sale>& sales) const override {
std::string out = "product,cents";
for (const Sale& sale : sales) {
out += "\n" + sale.product + "," + std::to_string(sale.cents);
}
return out;
}
std::string fileExtension() const override { return ".csv"; }
};
// Nobody asked for Excel either: a placeholder.
class ExcelFormatter : public ReportFormatter {
public:
std::string format(const std::vector<Sale>&) const override {
throw std::logic_error("Excel support coming soon");
}
std::string fileExtension() const override { return ".xlsx"; }
};
class FormatterRegistry {
public:
void add(const std::string& name, std::unique_ptr<ReportFormatter> formatter) {
formatters_[name] = std::move(formatter);
}
const ReportFormatter& get(const std::string& name) const {
auto it = formatters_.find(name);
if (it == formatters_.end()) {
throw std::invalid_argument("Unknown format: " + name);
}
return *it->second;
}
private:
std::map<std::string, std::unique_ptr<ReportFormatter>> formatters_;
};
class ReportGenerator {
public:
ReportGenerator(const FormatterRegistry& registry, const std::string& formatName)
: formatter_(registry.get(formatName)) {}
std::string generate(const std::vector<Sale>& sales) const {
return formatter_.format(sales);
}
private:
const ReportFormatter& formatter_;
};
int main() {
FormatterRegistry registry;
registry.add("text", std::make_unique<TextFormatter>());
registry.add("csv", std::make_unique<CsvFormatter>());
registry.add("excel", std::make_unique<ExcelFormatter>());
std::vector<Sale> sales = {
{"Desk lamp", 1500000},
{"Office chair", 2350050},
{"Bookshelf", 875025},
};
ReportGenerator generator(registry, "text");
std::cout << generator.generate(sales) << "\n";
}// A sales report built for formats nobody asked for: the requirement is one
// text report, and the design makes room for CSV and Excel as well.
interface Sale {
product: string;
cents: number;
}
interface ReportFormatter {
format(sales: Sale[]): string;
fileExtension(): string;
}
// Whole cents as dollars and cents, the same in every locale
function dollars(cents: number): string {
const rest = cents % 100;
return `$${Math.floor(cents / 100)}.${rest < 10 ? "0" : ""}${rest}`;
}
class TextFormatter implements ReportFormatter {
format(sales: Sale[]): string {
const lines = ["Sales Report", "-".repeat(24)];
let total = 0;
for (const sale of sales) {
lines.push(`${sale.product}: ${dollars(sale.cents)}`);
total += sale.cents;
}
lines.push("-".repeat(24));
lines.push(`Total: ${dollars(total)}`);
return lines.join("\n");
}
fileExtension(): string {
return ".txt";
}
}
// Nobody asked for CSV.
class CsvFormatter implements ReportFormatter {
format(sales: Sale[]): string {
const rows = ["product,cents", ...sales.map((s) => `${s.product},${s.cents}`)];
return rows.join("\n");
}
fileExtension(): string {
return ".csv";
}
}
// Nobody asked for Excel either: a placeholder.
class ExcelFormatter implements ReportFormatter {
format(_sales: Sale[]): string {
throw new Error("Excel support coming soon");
}
fileExtension(): string {
return ".xlsx";
}
}
class FormatterRegistry {
private formatters = new Map<string, ReportFormatter>();
add(name: string, formatter: ReportFormatter): void {
this.formatters.set(name, formatter);
}
get(name: string): ReportFormatter {
const formatter = this.formatters.get(name);
if (formatter === undefined) {
throw new Error(`Unknown format: ${name}`);
}
return formatter;
}
}
class ReportGenerator {
private formatter: ReportFormatter;
constructor(registry: FormatterRegistry, formatName: string) {
this.formatter = registry.get(formatName);
}
generate(sales: Sale[]): string {
return this.formatter.format(sales);
}
}
function main(): void {
const registry = new FormatterRegistry();
registry.add("text", new TextFormatter());
registry.add("csv", new CsvFormatter());
registry.add("excel", new ExcelFormatter());
const sales: Sale[] = [
{ product: "Desk lamp", cents: 1500000 },
{ product: "Office chair", cents: 2350050 },
{ product: "Bookshelf", cents: 875025 },
];
const generator = new ReportGenerator(registry, "text");
console.log(generator.generate(sales));
}
main();using System;
using System.Collections.Generic;
// A sales report built for formats nobody asked for: the requirement is one
// text report, and the design makes room for CSV and Excel as well.
public record Sale(string Product, int Cents);
public interface IReportFormatter
{
string Format(List<Sale> sales);
string FileExtension();
}
public class TextFormatter : IReportFormatter
{
// Whole cents as dollars and cents, the same in every locale
public static string Dollars(int cents)
{
int rest = cents % 100;
return "$" + cents / 100 + "." + (rest < 10 ? "0" : "") + rest;
}
public string Format(List<Sale> sales)
{
var lines = new List<string> { "Sales Report", new string('-', 24) };
int total = 0;
foreach (Sale sale in sales)
{
lines.Add(sale.Product + ": " + Dollars(sale.Cents));
total += sale.Cents;
}
lines.Add(new string('-', 24));
lines.Add("Total: " + Dollars(total));
return string.Join("\n", lines);
}
public string FileExtension() => ".txt";
}
// Nobody asked for CSV.
public class CsvFormatter : IReportFormatter
{
public string Format(List<Sale> sales)
{
var rows = new List<string> { "product,cents" };
foreach (Sale sale in sales)
{
rows.Add(sale.Product + "," + sale.Cents);
}
return string.Join("\n", rows);
}
public string FileExtension() => ".csv";
}
// Nobody asked for Excel either: a placeholder.
public class ExcelFormatter : IReportFormatter
{
public string Format(List<Sale> sales)
{
throw new NotImplementedException("Excel support coming soon");
}
public string FileExtension() => ".xlsx";
}
public class FormatterRegistry
{
private readonly Dictionary<string, IReportFormatter> formatters = new();
public void Add(string name, IReportFormatter formatter)
{
formatters[name] = formatter;
}
public IReportFormatter Get(string name)
{
if (!formatters.TryGetValue(name, out var formatter))
{
throw new ArgumentException("Unknown format: " + name);
}
return formatter;
}
}
public class ReportGenerator
{
private readonly IReportFormatter formatter;
public ReportGenerator(FormatterRegistry registry, string formatName)
{
formatter = registry.Get(formatName);
}
public string Generate(List<Sale> sales) => formatter.Format(sales);
}
public class ReportApp
{
public static void Main()
{
var registry = new FormatterRegistry();
registry.Add("text", new TextFormatter());
registry.Add("csv", new CsvFormatter());
registry.Add("excel", new ExcelFormatter());
var sales = new List<Sale>
{
new Sale("Desk lamp", 1500000),
new Sale("Office chair", 2350050),
new Sale("Bookshelf", 875025),
};
var generator = new ReportGenerator(registry, "text");
Console.WriteLine(generator.Generate(sales));
}
}package main
import (
"errors"
"fmt"
"strings"
)
// A sales report built for formats nobody asked for: the requirement is one
// text report, and the design makes room for CSV and Excel as well.
type Sale struct {
Product string
Cents int
}
type ReportFormatter interface {
Format(sales []Sale) string
FileExtension() string
}
// dollars writes whole cents as dollars and cents, the same in every locale.
func dollars(cents int) string {
return fmt.Sprintf("$%d.%02d", cents/100, cents%100)
}
type TextFormatter struct{}
func (TextFormatter) Format(sales []Sale) string {
lines := []string{"Sales Report", strings.Repeat("-", 24)}
total := 0
for _, sale := range sales {
lines = append(lines, sale.Product+": "+dollars(sale.Cents))
total += sale.Cents
}
lines = append(lines, strings.Repeat("-", 24))
lines = append(lines, "Total: "+dollars(total))
return strings.Join(lines, "\n")
}
func (TextFormatter) FileExtension() string { return ".txt" }
// CsvFormatter: nobody asked for CSV.
type CsvFormatter struct{}
func (CsvFormatter) Format(sales []Sale) string {
rows := []string{"product,cents"}
for _, sale := range sales {
rows = append(rows, fmt.Sprintf("%s,%d", sale.Product, sale.Cents))
}
return strings.Join(rows, "\n")
}
func (CsvFormatter) FileExtension() string { return ".csv" }
// ExcelFormatter: nobody asked for Excel either, a placeholder.
type ExcelFormatter struct{}
func (ExcelFormatter) Format(sales []Sale) string {
panic("Excel support coming soon")
}
func (ExcelFormatter) FileExtension() string { return ".xlsx" }
type FormatterRegistry struct {
formatters map[string]ReportFormatter
}
func NewFormatterRegistry() *FormatterRegistry {
return &FormatterRegistry{formatters: map[string]ReportFormatter{}}
}
func (r *FormatterRegistry) Add(name string, formatter ReportFormatter) {
r.formatters[name] = formatter
}
func (r *FormatterRegistry) Get(name string) (ReportFormatter, error) {
formatter, ok := r.formatters[name]
if !ok {
return nil, errors.New("Unknown format: " + name)
}
return formatter, nil
}
type ReportGenerator struct {
formatter ReportFormatter
}
func NewReportGenerator(r *FormatterRegistry, name string) (*ReportGenerator, error) {
formatter, err := r.Get(name)
if err != nil {
return nil, err
}
return &ReportGenerator{formatter: formatter}, nil
}
func (g *ReportGenerator) Generate(sales []Sale) string {
return g.formatter.Format(sales)
}
func main() {
registry := NewFormatterRegistry()
registry.Add("text", TextFormatter{})
registry.Add("csv", CsvFormatter{})
registry.Add("excel", ExcelFormatter{})
sales := []Sale{
{"Desk lamp", 1500000},
{"Office chair", 2350050},
{"Bookshelf", 875025},
}
generator, err := NewReportGenerator(registry, "text")
if err != nil {
fmt.Println(err)
return
}
fmt.Println(generator.Generate(sales))
}It prints:
Sales Report
------------------------
Desk lamp: $15000.00
Office chair: $23500.50
Bookshelf: $8750.25
------------------------
Total: $47250.75
Three formatters are made and registered, and only the text one ever runs. CsvFormatter is never asked for. ExcelFormatter is a placeholder that only throws "Excel support coming soon". file_extension, written for a day when reports are saved to files, is never called at all. A reader who wants to know how the report is made has to go through the generator and the registry to find the one class that does the work. Fowler quotes Jeremy Miller on exactly this: "any extensibility point that’s never used isn’t just wasted effort, it’s likely to also get in your way as well".
Only What Was Asked For
Here is the same requirement met directly, with one function.
# The same requirement, met directly: one function writes the report.
from dataclasses import dataclass
@dataclass(frozen=True)
class Sale:
product: str
cents: int
# Whole cents as dollars and cents, the same in every locale
def dollars(cents: int) -> str:
return f"${cents // 100}.{cents % 100:02d}"
def sales_report(sales: list[Sale]) -> str:
lines = ["Sales Report", "-" * 24]
for sale in sales:
lines.append(f"{sale.product}: {dollars(sale.cents)}")
lines.append("-" * 24)
lines.append(f"Total: {dollars(sum(s.cents for s in sales))}")
return "\n".join(lines)
def main() -> None:
sales = [
Sale("Desk lamp", 1500000),
Sale("Office chair", 2350050),
Sale("Bookshelf", 875025),
]
print(sales_report(sales))
if __name__ == "__main__":
main()import java.util.ArrayList;
import java.util.List;
// The same requirement, met directly: one function writes the report.
record Sale(String product, int cents) {}
public class Reports {
// Whole cents as dollars and cents, the same in every locale
static String dollars(int cents) {
int rest = cents % 100;
return "$" + cents / 100 + "." + (rest < 10 ? "0" : "") + rest;
}
static String salesReport(List<Sale> sales) {
List<String> lines = new ArrayList<>(List.of("Sales Report", "-".repeat(24)));
int total = 0;
for (Sale sale : sales) {
lines.add(sale.product() + ": " + dollars(sale.cents()));
total += sale.cents();
}
lines.add("-".repeat(24));
lines.add("Total: " + dollars(total));
return String.join("\n", lines);
}
public static void main(String[] args) {
List<Sale> sales = List.of(
new Sale("Desk lamp", 1500000),
new Sale("Office chair", 2350050),
new Sale("Bookshelf", 875025));
System.out.println(salesReport(sales));
}
}#include <iostream>
#include <string>
#include <vector>
// The same requirement, met directly: one function writes the report.
struct Sale {
std::string product;
int cents;
};
// Whole cents as dollars and cents, the same in every locale
std::string dollars(int cents) {
int rest = cents % 100;
return "$" + std::to_string(cents / 100) + "." + (rest < 10 ? "0" : "") +
std::to_string(rest);
}
std::string salesReport(const std::vector<Sale>& sales) {
std::string out = "Sales Report\n" + std::string(24, '-') + "\n";
int total = 0;
for (const Sale& sale : sales) {
out += sale.product + ": " + dollars(sale.cents) + "\n";
total += sale.cents;
}
out += std::string(24, '-') + "\n";
out += "Total: " + dollars(total);
return out;
}
int main() {
std::vector<Sale> sales = {
{"Desk lamp", 1500000},
{"Office chair", 2350050},
{"Bookshelf", 875025},
};
std::cout << salesReport(sales) << "\n";
}// The same requirement, met directly: one function writes the report.
interface Sale {
product: string;
cents: number;
}
// Whole cents as dollars and cents, the same in every locale
function dollars(cents: number): string {
const rest = cents % 100;
return `$${Math.floor(cents / 100)}.${rest < 10 ? "0" : ""}${rest}`;
}
function salesReport(sales: Sale[]): string {
const lines = ["Sales Report", "-".repeat(24)];
let total = 0;
for (const sale of sales) {
lines.push(`${sale.product}: ${dollars(sale.cents)}`);
total += sale.cents;
}
lines.push("-".repeat(24));
lines.push(`Total: ${dollars(total)}`);
return lines.join("\n");
}
function main(): void {
const sales: Sale[] = [
{ product: "Desk lamp", cents: 1500000 },
{ product: "Office chair", cents: 2350050 },
{ product: "Bookshelf", cents: 875025 },
];
console.log(salesReport(sales));
}
main();using System;
using System.Collections.Generic;
// The same requirement, met directly: one function writes the report.
public record Sale(string Product, int Cents);
public class Reports
{
// Whole cents as dollars and cents, the same in every locale
public static string Dollars(int cents)
{
int rest = cents % 100;
return "$" + cents / 100 + "." + (rest < 10 ? "0" : "") + rest;
}
public static string SalesReport(List<Sale> sales)
{
var lines = new List<string> { "Sales Report", new string('-', 24) };
int total = 0;
foreach (Sale sale in sales)
{
lines.Add(sale.Product + ": " + Dollars(sale.Cents));
total += sale.Cents;
}
lines.Add(new string('-', 24));
lines.Add("Total: " + Dollars(total));
return string.Join("\n", lines);
}
public static void Main()
{
var sales = new List<Sale>
{
new Sale("Desk lamp", 1500000),
new Sale("Office chair", 2350050),
new Sale("Bookshelf", 875025),
};
Console.WriteLine(SalesReport(sales));
}
}package main
import (
"fmt"
"strings"
)
// The same requirement, met directly: one function writes the report.
type Sale struct {
Product string
Cents int
}
// dollars writes whole cents as dollars and cents, the same in every locale.
func dollars(cents int) string {
return fmt.Sprintf("$%d.%02d", cents/100, cents%100)
}
func salesReport(sales []Sale) string {
lines := []string{"Sales Report", strings.Repeat("-", 24)}
total := 0
for _, sale := range sales {
lines = append(lines, sale.Product+": "+dollars(sale.Cents))
total += sale.Cents
}
lines = append(lines, strings.Repeat("-", 24))
lines = append(lines, "Total: "+dollars(total))
return strings.Join(lines, "\n")
}
func main() {
sales := []Sale{
{"Desk lamp", 1500000},
{"Office chair", 2350050},
{"Bookshelf", 875025},
}
fmt.Println(salesReport(sales))
}It prints:
Sales Report
------------------------
Desk lamp: $15000.00
Office chair: $23500.50
Bookshelf: $8750.25
------------------------
Total: $47250.75
The same report, line for line. The body of sales_report is the body of TextFormatter.format from the first program: that formatter was the only part the requirement needed, and everything around it was room made for guesses.
If the finance team does ask for a CSV file one day, that is the time to write it, from their real request: which columns they want, in what order, and how amounts should be written. Those details are hard to guess in advance. The early CsvFormatter, which writes raw cents under the header product,cents, would most likely have needed rewriting to match them, which is Fowler's cost of repair.
But What If We Need It Later?
The usual answer to YAGNI is that adding a feature later will cost more than adding it now. When developers tell Fowler that, he asks them to imagine the refactoring they would do later to bring the feature in when it is needed: "Often that thought experiment is enough to convince them that it won't be significantly more expensive to add it later." The same exercise sometimes turns up a small step that is worth taking now, because it is easy, "adds minimal complexity, yet significantly reduces the later cost". His example is keeping error messages in a lookup table instead of writing each one inline, which makes translating them later much easier.
Waiting only works when the code is easy to change, and Fowler is direct about it. YAGNI rests on refactoring (improving the code's structure without changing what it does), on self-testing code (automated tests that check the program every time it changes) and on continuous delivery (keeping every change ready to release). Without them, he writes, "yagni turns from a beneficial practice into a curse."
He also admits that YAGNI sometimes loses: now and then, waiting leads to an expensive change that would have been cheap earlier. Such cases are hard to see in advance and easy to remember afterwards, and his judgement is that "yagni-failures are relatively rare and their costs are easily outweighed by when yagni succeeds."
The rule also applies to small decisions, which come up more often than big ones. Jeffries' own example is a single method: "You find that you need a getter for some instance variable. Fine, write it. Don’t write the setter because “we’re going to need it”."
Common Mistakes
Using YAGNI as an excuse for messy code. "YAGNI says not to over-build, so I'll write the database address into every file and skip the tests." YAGNI is about features and the structure built for them, and Fowler draws the line clearly: "Yagni only applies to capabilities built into the software to support a presumptive feature, it does not apply to effort to make the software easier to modify." Keeping settings out of the code, splitting a long function and writing tests all make today's code easier to change, which is exactly what waiting needs. In his words, "Yagni is not a justification for neglecting the health of your code base."
Refusing the abstraction when the need arrives. YAGNI says to wait for the need, and to act once it is here. When a second report format, a second payment provider or a third notification channel is really requested, that is the moment to bring in the interface. Fowler does not ask for code without abstractions either; his rule is that "any abstraction that makes it harder to understand the code for current requirements is presumed guilty."
Adding features while you are in there. "I'm already changing the payment code, so I'll add cryptocurrency payments too, though nobody has asked for them." Being in a file is no reason to add to it. Finish the change you came to make and ship it; cryptocurrency payments can wait until someone needs them.
YAGNI, KISS and DRY
YAGNI sits beside DRY — Don't Repeat Yourself and KISS — Keep It Simple, Stupid, and each one catches a different kind of needless code. DRY asks whether each piece of knowledge has one home, and KISS whether a design is the simplest one that meets the requirement. YAGNI asks an earlier question, whether the requirement exists yet. A design can be simple and free of copies and still be built for a need nobody has.
They also keep each other in check. Folding two real copies of a rule into one function is DRY at work. Building a general framework today, so that copies nobody has written yet will have a home, is the mistake YAGNI warns against.
Separation of Concerns — One Job per Part comes next: how to divide a program into parts that each do one job.
Key Takeaways
- YAGNI means building a capability when it is actually needed, never because you foresee needing it.
- A feature built early can cost its whole build if it is never used; even when it is, it delays what is needed now, makes every other change harder while it waits, and may need repair by the time it is used.
- YAGNI depends on code that is easy to change, so refactoring, automated tests and a release process that is ready at any time are part of practising it.
- When the need really arrives, add the feature or the abstraction then, from the real request.