{"id":"6b09a4c1ff996234422a276a","slug":"yagni","title":"YAGNI: nie buduj na zapas – ile kosztuje funkcja, której nikt nie zamówił","summary":"Zasada YAGNI na przykładzie sklepu internetowego pierogarni Haliny: pochodzenie z Extreme Programming, cztery koszty funkcji budowanej na zapas, YAGNI a punkty rozszerzeń i flagi funkcji oraz usuwanie przedwczesnej abstrakcji z kodu płatności w C#, TypeScript, Javie, Go i Pythonie.","servedLang":"pl","availableLangs":["pl","en"],"topics":["yagni","kiss","modular-monolith"],"techs":["dotnet","typescript","java","go","python"],"tags":["yagni","principles","extreme-programming","speculative-generality","feature-flags","refactoring"],"level":"beginner","kind":"article","access":"members","status":"published","cover":null,"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"readingMinutes":16,"stats":{"views":0,"likes":0,"bookmarks":0,"comments":0},"publishedAt":"2026-11-27T15:41:53.238Z","updatedAt":"2026-11-27T15:41:53.847Z","requestedLang":"pl","theme":{"hero":"classic","heroMedia":null,"accent":"amber","background":"hex","weaveResources":true,"toc":"right"},"seoDescription":"YAGNI (You Aren't Gonna Need It) w praktyce: pochodzenie z XP, koszt utrzymania funkcji na zapas (cost of carry), YAGNI kontra rozszerzalność i OCP, flagi funkcji, przykłady przedwczesnej abstrakcji i refaktoryzacja w C#, TypeScript, Java, Go i Python.","wordCount":3184,"doc":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"Gdy pierogarnia Haliny wchodziła do internetu, programista „na wszelki wypadek” przygotował obsługę euro i koron, fabrykę operatorów płatności i wielodostępność pod przyszłą franczyzę. Po roku sklep przyjął zero zamówień w euro, operator płatności jest jeden, a lokal – nadal jeden. Kod jednak został i każdą zmianę w koszyku trzeba przeprowadzać przez warstwy, które niczemu nie służą. "},{"type":"text","text":"YAGNI","marks":[{"type":"bold"}]},{"type":"text","text":" (ang. "},{"type":"text","text":"You Aren't Gonna Need It","marks":[{"type":"italic"}]},{"type":"text","text":" – „nie będziesz tego potrzebować”) to zasada, by budować funkcje wtedy, gdy są potrzebne, a nie wtedy, gdy się je przewiduje."}]},{"type":"callout","attrs":{"variant":"tip","title":"W skrócie"},"content":[{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Buduj to, czego potrzebujesz teraz; przewidywania zapisuj w backlogu, a nie w kodzie."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Funkcja na zapas kosztuje nie tylko przy budowie: spowalnia każdą kolejną zmianę i często trzeba ją przerabiać, gdy przyjdą prawdziwe wymagania."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"YAGNI nie dotyczy tego, co ułatwia zmiany – testów, refaktoryzacji, czytelnego kodu. To robisz zawsze."}]}]}]}]},{"type":"stats","attrs":{"items":[{"value":"1999","label":"„Extreme Programming Explained”","hint":"Kent Beck opisuje XP i prosty projekt"},{"value":"4","label":"koszty funkcji na zapas","hint":"budowa, opóźnienie, utrzymanie i naprawa – według Martina Fowlera"},{"value":"0","label":"zamówień w euro po roku","hint":"a obsługa walut dotyka każdej zmiany w koszyku"}]}},{"type":"heading","attrs":{"level":2,"id":"skad-sie-wzielo-yagni"},"content":[{"type":"text","text":"Skąd się wzięło YAGNI"}]},{"type":"paragraph","content":[{"type":"text","text":"YAGNI to jedna z mantr Extreme Programming (XP) – metodyki, która zamiast projektować wszystko z góry, każe dostarczać małe przyrosty i ciągle poprawiać projekt."}]},{"type":"timeline","attrs":{"items":[{"date":"1996","title":"Projekt C3 w Chryslerze","text":"Kent Beck obejmuje projekt i razem z zespołem (m.in. Ronem Jeffriesem) układa praktyki, które staną się Extreme Programming."},{"date":"1999","title":"„Extreme Programming Explained”","text":"Kent Beck opisuje XP; prosty projekt (ang. *simple design*) jest jedną z jego praktyk."},{"date":"2001","title":"Manifest Agile","text":"Wśród zasad: prostota – sztuka maksymalizacji ilości pracy, której nie trzeba wykonać – jest kluczowa."},{"date":"2015","title":"Martin Fowler, „Yagni”","text":"Rozpisanie czterech kosztów funkcji budowanej na zapas i granic stosowania zasady."}]}},{"type":"pullQuote","attrs":{"text":"Zawsze implementuj rzeczy wtedy, gdy rzeczywiście ich potrzebujesz, nigdy wtedy, gdy tylko przewidujesz, że będą potrzebne.","author":"Ron Jeffries","role":"współtwórca Extreme Programming"}},{"type":"heading","attrs":{"level":2,"id":"problem-sklep-zbudowany-pod-przyszlosc-ktora-nie-przyszla"},"content":[{"type":"text","text":"Problem: sklep zbudowany pod przyszłość, która nie przyszła"}]},{"type":"paragraph","content":[{"type":"text","text":"Kod płatności po roku działania sklepu. Wszystkie punkty rozszerzeń powstały pierwszego dnia, a żaden nie został użyty:"}]},{"type":"codeGroup","attrs":{"title":"Przed – płatności z punktami rozszerzeń na zapas"},"content":[{"type":"codeBlock","attrs":{"language":"csharp","filename":"Payments.cs"},"content":[{"type":"text","text":"// Before: built \"for the future\" – one operator, one currency, three extension points.\nvar factory = new PaymentGatewayFactory(new PlnOnlyRates());\nvar gateway = factory.Create(GatewayKind.CardOperator);\nConsole.WriteLine(gateway.Charge(\"A-1042\", new Money(45.90m, \"PLN\")));\n\npublic sealed record Money(decimal Amount, string Currency);\n\npublic interface IExchangeRates { decimal ToPln(string currency); }\n\npublic sealed class PlnOnlyRates : IExchangeRates\n{\n    // The only currency we have seen in two years.\n    public decimal ToPln(string currency) =>\n        currency == \"PLN\" ? 1m : throw new NotSupportedException($\"No rates for {currency} yet\");\n}\n\npublic enum GatewayKind { CardOperator } // \"we will add more providers later\"\n\npublic interface IPaymentGateway { string Charge(string orderId, Money amount); }\n\npublic sealed class CardOperatorGateway(IExchangeRates rates) : IPaymentGateway\n{\n    public string Charge(string orderId, Money amount)\n    {\n        var pln = amount.Amount * rates.ToPln(amount.Currency);\n        return $\"Charged {pln} PLN for order {orderId}\"; // the real HTTP call goes here\n    }\n}\n\npublic sealed class PaymentGatewayFactory(IExchangeRates rates)\n{\n    public IPaymentGateway Create(GatewayKind kind) => kind switch\n    {\n        GatewayKind.CardOperator => new CardOperatorGateway(rates),\n        _ => throw new NotSupportedException($\"Unknown gateway {kind}\"),\n    };\n}"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"payments.ts"},"content":[{"type":"text","text":"// Before: built \"for the future\" – one operator, one currency, three extension points.\ninterface Money { amount: number; currency: string } // amount in minor units\ninterface ExchangeRates { toPln(currency: string): number }\n\nconst plnOnlyRates: ExchangeRates = {\n  toPln(currency) {\n    if (currency !== 'PLN') throw new Error(`No rates for ${currency} yet`); // the only currency in two years\n    return 1;\n  },\n};\n\ntype GatewayKind = 'card-operator'; // \"we will add more providers later\"\n\ninterface PaymentGateway { charge(orderId: string, amount: Money): string }\n\nclass CardOperatorGateway implements PaymentGateway {\n  constructor(private readonly rates: ExchangeRates) {}\n  charge(orderId: string, amount: Money): string {\n    const grosze = amount.amount * this.rates.toPln(amount.currency);\n    return `Charged ${(grosze / 100).toFixed(2)} PLN for order ${orderId}`; // the real HTTP call goes here\n  }\n}\n\nclass PaymentGatewayFactory {\n  constructor(private readonly rates: ExchangeRates) {}\n  create(kind: GatewayKind): PaymentGateway {\n    switch (kind) {\n      case 'card-operator':\n        return new CardOperatorGateway(this.rates);\n      default:\n        throw new Error(`Unknown gateway ${String(kind)}`);\n    }\n  }\n}\n\nconst gateway = new PaymentGatewayFactory(plnOnlyRates).create('card-operator');\nconsole.log(gateway.charge('A-1042', { amount: 4_590, currency: 'PLN' }));"}]},{"type":"codeBlock","attrs":{"language":"java","filename":"Payments.java"},"content":[{"type":"text","text":"import java.math.BigDecimal;\n\n// Before: built \"for the future\" – one operator, one currency, three extension points.\npublic class Payments {\n    public static void main(String[] args) {\n        var gateway = new PaymentGatewayFactory(new PlnOnlyRates()).create(GatewayKind.CARD_OPERATOR);\n        System.out.println(gateway.charge(\"A-1042\", new Money(new BigDecimal(\"45.90\"), \"PLN\")));\n    }\n}\n\nrecord Money(BigDecimal amount, String currency) {}\n\ninterface ExchangeRates { BigDecimal toPln(String currency); }\n\nclass PlnOnlyRates implements ExchangeRates {\n    // The only currency we have seen in two years.\n    public BigDecimal toPln(String currency) {\n        if (!currency.equals(\"PLN\")) throw new UnsupportedOperationException(\"No rates for \" + currency + \" yet\");\n        return BigDecimal.ONE;\n    }\n}\n\nenum GatewayKind { CARD_OPERATOR } // \"we will add more providers later\"\n\ninterface PaymentGateway { String charge(String orderId, Money amount); }\n\nrecord CardOperatorGateway(ExchangeRates rates) implements PaymentGateway {\n    public String charge(String orderId, Money amount) {\n        var pln = amount.amount().multiply(rates.toPln(amount.currency()));\n        return \"Charged \" + pln + \" PLN for order \" + orderId; // the real HTTP call goes here\n    }\n}\n\nrecord PaymentGatewayFactory(ExchangeRates rates) {\n    PaymentGateway create(GatewayKind kind) {\n        return switch (kind) {\n            case CARD_OPERATOR -> new CardOperatorGateway(rates);\n        };\n    }\n}"}]},{"type":"codeBlock","attrs":{"language":"go","filename":"payments.go"},"content":[{"type":"text","text":"package main\n\nimport \"fmt\"\n\n// Before: built \"for the future\" – one operator, one currency, three extension points.\ntype Money struct {\n\tAmount   int64 // minor units\n\tCurrency string\n}\n\ntype ExchangeRates interface{ ToPLN(currency string) (int64, error) }\n\ntype PLNOnlyRates struct{}\n\n// The only currency we have seen in two years.\nfunc (PLNOnlyRates) ToPLN(currency string) (int64, error) {\n\tif currency != \"PLN\" {\n\t\treturn 0, fmt.Errorf(\"no rates for %s yet\", currency)\n\t}\n\treturn 1, nil\n}\n\ntype GatewayKind int\n\nconst CardOperator GatewayKind = iota // \"we will add more providers later\"\n\ntype PaymentGateway interface {\n\tCharge(orderID string, amount Money) (string, error)\n}\n\ntype CardOperatorGateway struct{ rates ExchangeRates }\n\nfunc (g CardOperatorGateway) Charge(orderID string, amount Money) (string, error) {\n\trate, err := g.rates.ToPLN(amount.Currency)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tgrosze := amount.Amount * rate // the real HTTP call goes here\n\treturn fmt.Sprintf(\"Charged %d.%02d PLN for order %s\", grosze/100, grosze%100, orderID), nil\n}\n\nfunc NewGateway(kind GatewayKind, rates ExchangeRates) (PaymentGateway, error) {\n\tswitch kind {\n\tcase CardOperator:\n\t\treturn CardOperatorGateway{rates: rates}, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown gateway %d\", kind)\n\t}\n}\n\nfunc main() {\n\tgateway, _ := NewGateway(CardOperator, PLNOnlyRates{})\n\tfmt.Println(gateway.Charge(\"A-1042\", Money{Amount: 4590, Currency: \"PLN\"}))\n}"}]},{"type":"codeBlock","attrs":{"language":"python","filename":"payments.py"},"content":[{"type":"text","text":"from dataclasses import dataclass\nfrom decimal import Decimal\nfrom enum import Enum\nfrom typing import Protocol\n\n\n# Before: built \"for the future\" – one operator, one currency, three extension points.\n@dataclass(frozen=True)\nclass Money:\n    amount: Decimal\n    currency: str\n\n\nclass ExchangeRates(Protocol):\n    def to_pln(self, currency: str) -> Decimal: ...\n\n\nclass PlnOnlyRates:\n    def to_pln(self, currency: str) -> Decimal:\n        if currency != \"PLN\":  # the only currency we have seen in two years\n            raise NotImplementedError(f\"No rates for {currency} yet\")\n        return Decimal(\"1\")\n\n\nclass GatewayKind(Enum):\n    CARD_OPERATOR = \"card-operator\"  # \"we will add more providers later\"\n\n\nclass PaymentGateway(Protocol):\n    def charge(self, order_id: str, amount: Money) -> str: ...\n\n\nclass CardOperatorGateway:\n    def __init__(self, rates: ExchangeRates) -> None:\n        self._rates = rates\n\n    def charge(self, order_id: str, amount: Money) -> str:\n        pln = amount.amount * self._rates.to_pln(amount.currency)\n        return f\"Charged {pln} PLN for order {order_id}\"  # the real HTTP call goes here\n\n\nclass PaymentGatewayFactory:\n    def __init__(self, rates: ExchangeRates) -> None:\n        self._rates = rates\n\n    def create(self, kind: GatewayKind) -> PaymentGateway:\n        match kind:\n            case GatewayKind.CARD_OPERATOR:\n                return CardOperatorGateway(self._rates)\n        raise ValueError(f\"Unknown gateway {kind}\")\n\n\ngateway = PaymentGatewayFactory(PlnOnlyRates()).create(GatewayKind.CARD_OPERATOR)\nprint(gateway.charge(\"A-1042\", Money(Decimal(\"45.90\"), \"PLN\")))"}]}]}]},"toc":[{"id":"skad-sie-wzielo-yagni","text":"Skąd się wzięło YAGNI","level":2,"locked":false},{"id":"problem-sklep-zbudowany-pod-przyszlosc-ktora-nie-przyszla","text":"Problem: sklep zbudowany pod przyszłość, która nie przyszła","level":2,"locked":false},{"id":"ile-kosztuje-funkcja-na-zapas","text":"Ile kosztuje funkcja na zapas","level":2,"locked":true},{"id":"rozwiazanie-usun-spekulatywna-ogolnosc","text":"Rozwiązanie: usuń spekulatywną ogólność","level":2,"locked":true},{"id":"yagni-a-punkty-rozszerzen","text":"YAGNI a punkty rozszerzeń","level":2,"locked":true},{"id":"flagi-funkcji","text":"Flagi funkcji","level":2,"locked":true},{"id":"przyklady-przedwczesnej-abstrakcji","text":"Przykłady przedwczesnej abstrakcji","level":2,"locked":true},{"id":"kiedy-stosowac-a-kiedy-nie","text":"Kiedy stosować, a kiedy nie","level":2,"locked":true},{"id":"w-praktyce","text":"W praktyce","level":2,"locked":true},{"id":"powiazania","text":"Powiązania","level":2,"locked":true},{"id":"sprawdz-sie","text":"Sprawdź się","level":2,"locked":true}],"locked":true,"paywall":null,"previewRatio":0.3,"totalBlocks":51,"visibleBlocks":10,"resources":[{"id":"6b0857b53c96f2d34d0b38fd","type":"article","provider":"web","url":"https://martinfowler.com/bliki/Yagni.html","embedUrl":null,"title":"Yagni","description":"Yagni (\"You Aren't Gonna Need It\") is the principle that we should not build presumptive features. It should not be used as a justification for neglecting internal quality.","author":"martinfowler.com","thumbnailUrl":"https://martinfowler.com/bliki/images/yagni/sketch.png","durationSec":null,"lang":"en","topics":["yagni"],"techs":["general"],"tags":["hacker-news"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"hn","publishedAt":"2015-05-26T16:17:12.000Z","popularity":70,"verifiedAt":"2026-11-26T11:07:40.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:52.228Z","updatedAt":"2026-11-26T16:00:52.228Z"},{"id":"6b0857b53c96f2d34d0b3a38","type":"article","provider":"web","url":"https://newsletter.kentbeck.com/p/the-cost-yagni-was-never-about","embedUrl":null,"title":"The cost YAGNI was never about","description":"If you think YAGNI is about saving effort, cheap generation should retire it. It doesn't. Here's why.","author":"Kent Beck","thumbnailUrl":"https://substackcdn.com/image/fetch/$s_!glPN!,f_auto,q_auto:best,fl_progressive:steep/https%3A%2F%2Ftidyfirst.substack.com%2Ftwitter%2Fsubscribe-card.jpg%3Fv%3D1077263058%26version%3D9","durationSec":null,"lang":"en","topics":["yagni"],"techs":["general"],"tags":["hacker-news"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"hn","publishedAt":"2026-06-28T18:31:54.000Z","popularity":61,"verifiedAt":"2026-11-26T11:07:40.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:52.228Z","updatedAt":"2026-11-26T16:00:52.228Z"},{"id":"6b0857b53c96f2d34d0b38da","type":"article","provider":"web","url":"https://lukeplant.me.uk/blog/posts/yagni-exceptions","embedUrl":null,"title":"Yagni Exceptions (2021)","description":"A list of some exceptions to the principle of “You Ain't Gonna Need It” – that is, times when doing a bit more up front usually pays off.","author":"Luke Plant","thumbnailUrl":null,"durationSec":null,"lang":"en","topics":["yagni"],"techs":["general"],"tags":["hacker-news"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"hn","publishedAt":"2022-10-17T06:03:48.000Z","popularity":71,"verifiedAt":"2026-11-26T11:07:40.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:52.228Z","updatedAt":"2026-11-26T16:00:52.228Z"},{"id":"6b0857c33c96f2d34d0b4670","type":"book","provider":"openlibrary","url":"https://openlibrary.org/works/OL1961693W","embedUrl":null,"title":"Extreme programming explained","description":"","author":"Kent Beck, Cynthia Andres","thumbnailUrl":"https://covers.openlibrary.org/b/id/5394766-L.jpg","durationSec":null,"lang":"en","topics":[],"techs":["general"],"tags":["book"],"price":"paid","featured":false,"featuredOrder":0,"packageName":null,"source":"openlibrary","publishedAt":"1999-01-01T00:00:00.000Z","popularity":59,"verifiedAt":"2026-11-26T11:00:08.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:04.995Z","updatedAt":"2026-11-26T16:01:04.995Z"},{"id":"6b0857be3c96f2d34d0b420c","type":"article","provider":"web","url":"https://martinfowler.com/articles/feature-toggles.html","embedUrl":null,"title":"Feature Toggles (aka Feature Flags)","description":"Feature Flags can be categorized into several buckets; manage each appropriately. Smart implementation can help constrain complexity.","author":"Martin Fowler","thumbnailUrl":"https://martinfowler.com/articles/feature-toggles/overview-diagram.png","durationSec":null,"lang":"en","topics":[],"techs":["general"],"tags":["martin-fowler"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"manual","publishedAt":null,"popularity":75,"verifiedAt":"2026-11-26T11:07:20.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:59.965Z","updatedAt":"2026-11-26T16:00:59.965Z"},{"id":"6b0857c63c96f2d34d0b48da","type":"video","provider":"youtube","url":"https://www.youtube.com/watch?v=flxmpq7_tdM","embedUrl":"https://www.youtube-nocookie.com/embed/flxmpq7_tdM","title":"How To Avoid Designing A Big Ball Of Mud (YAGNI)","description":"What is good design and how can we tell the difference between that and bad software design? Extreme Programming introduced some key ideas about software design, that often get overlooked. YAGNI, “You Ain’t Gonna Need It”, and an evolutionary design approach that Kent Beck referred to as \"design…","author":"Modern Software Engineering","thumbnailUrl":"https://i.ytimg.com/vi/flxmpq7_tdM/hqdefault.jpg","durationSec":null,"lang":"en","topics":["yagni"],"techs":["general"],"tags":["refactoring","legacy-code"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"youtube-rss","publishedAt":"2022-09-21T18:00:15.000Z","popularity":68,"verifiedAt":"2026-11-26T11:13:34.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:10.095Z","updatedAt":"2026-11-26T16:01:10.095Z"}],"challenges":[],"attachments":[],"hasCode":true,"repoUrl":null,"series":[{"slug":"design-principles","title":"Zasady projektowania","items":[{"slug":"kiss","title":"KISS: najprostsze działające rozwiązanie zwykle wygrywa","current":false},{"slug":"dry","title":"DRY: jedna wiedza, jedno miejsce – i kiedy duplikacja jest tańsza","current":false},{"slug":"yagni","title":"YAGNI: nie buduj na zapas – ile kosztuje funkcja, której nikt nie zamówił","current":true},{"slug":"law-of-demeter","title":"Prawo Demeter: rozmawiaj tylko z przyjaciółmi","current":false},{"slug":"solid","title":"SOLID: pięć zasad projektowania obiektowego bez mitów","current":false}]}],"prev":{"slug":"dry","title":"DRY: jedna wiedza, jedno miejsce – i kiedy duplikacja jest tańsza"},"next":{"slug":"law-of-demeter","title":"Prawo Demeter: rozmawiaj tylko z przyjaciółmi"},"featured":false,"authorCard":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","headline":"Wzorce projektowe · Architektura · AI i LLM","community":false,"reputation":{"points":3900,"level":{"key":"mentor","label":"Mentor"}},"articles":104,"skills":[{"key":"typescript","title":"TypeScript","level":5,"levelLabel":"Autorytet","articles":90},{"key":"dotnet","title":".NET","level":5,"levelLabel":"Autorytet","articles":61},{"key":"python","title":"Python","level":5,"levelLabel":"Autorytet","articles":59},{"key":"java","title":"Java","level":5,"levelLabel":"Autorytet","articles":46}]}}