{"id":"6b09a4bfff996234422a2756","slug":"solid","title":"SOLID: pięć zasad projektowania obiektowego bez mitów","summary":"Zasady SOLID na przykładzie pierogarni Haliny: SRP, OCP, LSP, ISP i DIP – każda z naruszeniem i poprawką w C#, TypeScript, Javie, Go i Pythonie, z diagramami, wzorcami, które ją realizują, i najczęstszymi błędnymi interpretacjami.","servedLang":"pl","availableLangs":["pl","en"],"topics":["solid","strategy","decorator","adapter"],"techs":["dotnet","typescript","java","go","python"],"tags":["solid","principles","srp","open-closed","liskov","interface-segregation","dependency-inversion"],"level":"intermediate","kind":"article","access":"members","status":"published","cover":null,"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"readingMinutes":32,"stats":{"views":0,"likes":0,"bookmarks":0,"comments":0},"publishedAt":"2026-11-27T15:41:51.919Z","updatedAt":"2026-11-27T15:41:53.847Z","requestedLang":"pl","theme":{"hero":"classic","heroMedia":null,"accent":"amber","background":"dots","weaveResources":true,"toc":"right"},"seoDescription":"SOLID w praktyce: pojedyncza odpowiedzialność, otwarte–zamknięte, podstawienie Liskov, segregacja interfejsów i odwrócenie zależności – naruszenia i poprawki w C#, TypeScript, Java, Go i Python, wzorce (Strategia, Dekorator, Adapter) i mity, np. SRP to nie „jedna metoda”.","wordCount":6231,"doc":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"Kod sklepu pierogarni Haliny ma już kilka lat. Kuchnia, księgowość i marketing proszą o zmiany w tych samych klasach, każda nowa promocja to kolejny "},{"type":"text","text":"case","marks":[{"type":"code"}]},{"type":"text","text":", a test wyświetlacza w kuchni wymaga atrapy z sześcioma metodami. "},{"type":"text","text":"SOLID","marks":[{"type":"bold"}]},{"type":"text","text":" to pięć zasad zebranych przez Roberta C. Martina, które pomagają takiemu kodowi zmieniać się bez efektu domina. Nie są prawami fizyki – to heurystyki, które działają najlepiej wtedy, gdy rozumiesz, jaki problem rozwiązuje każda z nich."}]},{"type":"callout","attrs":{"variant":"tip","title":"W skrócie"},"content":[{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Każda zasada odpowiada na inne pytanie: kto prosi o zmiany (SRP), jak dodawać warianty (OCP), kiedy podtyp jest wymienny (LSP), ile klient musi wiedzieć (ISP), kto od kogo zależy (DIP)."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Wiele wzorców GoF to gotowe sposoby realizacji SOLID: Strategia i Dekorator dla OCP, Adapter dla DIP i ISP."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Najwięcej błędów bierze się z dosłownego czytania nazw: SRP to nie „jedna metoda”, a DIP to nie „kontener DI”."}]}]}]}]},{"type":"stats","attrs":{"items":[{"value":"5","label":"zasad","hint":"SRP, OCP, LSP, ISP, DIP"},{"value":"1987","label":"najstarsza z nich","hint":"Barbara Liskov i zasada podstawienia"},{"value":"ok. 2004","label":"akronim SOLID","hint":"ułożony przez Michaela Feathersa"}]}},{"type":"heading","attrs":{"level":2,"id":"skad-sie-wzielo-solid"},"content":[{"type":"text","text":"Skąd się wzięło SOLID"}]},{"type":"paragraph","content":[{"type":"text","text":"Zasady powstawały osobno i dopiero później trafiły do jednego worka:"}]},{"type":"timeline","attrs":{"items":[{"date":"1987","title":"Barbara Liskov","text":"Wykład „Data Abstraction and Hierarchy” na konferencji OOPSLA – zasada podstawienia."},{"date":"1988","title":"Bertrand Meyer","text":"„Object-Oriented Software Construction” – moduły otwarte na rozszerzanie, zamknięte na modyfikacje."},{"date":"1996","title":"Robert C. Martin","text":"Seria artykułów w C++ Report: otwarte–zamknięte, podstawienie Liskov, odwrócenie zależności, segregacja interfejsów."},{"date":"2000","title":"„Design Principles and Design Patterns”","text":"Martin zbiera zasady projektowania klas w jednym tekście."},{"date":"ok. 2004","title":"Michael Feathers","text":"Układa z pierwszych liter akronim SOLID."},{"date":"2017","title":"„Clean Architecture”","text":"Martin przeformułowuje SRP: moduł odpowiada przed jednym aktorem."}]}},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Litera"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Zasada"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Jednym zdaniem"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Wzorce, które ją realizują"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"S"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"pojedyncza odpowiedzialność ("},{"type":"text","text":"Single Responsibility","marks":[{"type":"italic"}]},{"type":"text","text":")"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"moduł odpowiada przed jednym aktorem"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Dekorator","marks":[{"type":"link","attrs":{"href":"/pl/topics/decorator"}}]},{"type":"text","text":", "},{"type":"text","text":"Obserwator","marks":[{"type":"link","attrs":{"href":"/pl/topics/observer"}}]},{"type":"text","text":", "},{"type":"text","text":"Polecenie","marks":[{"type":"link","attrs":{"href":"/pl/topics/command"}}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"O"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"otwarte–zamknięte ("},{"type":"text","text":"Open/Closed","marks":[{"type":"italic"}]},{"type":"text","text":")"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"nowe zachowanie dodajesz nowym kodem, nie edycją starego"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Strategia","marks":[{"type":"link","attrs":{"href":"/pl/topics/strategy"}}]},{"type":"text","text":", "},{"type":"text","text":"Dekorator","marks":[{"type":"link","attrs":{"href":"/pl/topics/decorator"}}]},{"type":"text","text":", "},{"type":"text","text":"Metoda szablonowa","marks":[{"type":"link","attrs":{"href":"/pl/topics/template-method"}}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"L"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"podstawienie Liskov ("},{"type":"text","text":"Liskov Substitution","marks":[{"type":"italic"}]},{"type":"text","text":")"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"podtyp spełnia kontrakt typu bazowego"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Kompozyt","marks":[{"type":"link","attrs":{"href":"/pl/topics/composite"}}]},{"type":"text","text":", "},{"type":"text","text":"Pełnomocnik","marks":[{"type":"link","attrs":{"href":"/pl/topics/proxy"}}]},{"type":"text","text":", "},{"type":"text","text":"Stan","marks":[{"type":"link","attrs":{"href":"/pl/topics/state"}}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"I"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"segregacja interfejsów ("},{"type":"text","text":"Interface Segregation","marks":[{"type":"italic"}]},{"type":"text","text":")"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"klient zależy tylko od metod, których używa"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Adapter","marks":[{"type":"link","attrs":{"href":"/pl/topics/adapter"}}]},{"type":"text","text":", "},{"type":"text","text":"Fasada","marks":[{"type":"link","attrs":{"href":"/pl/topics/facade"}}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"D"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"odwrócenie zależności ("},{"type":"text","text":"Dependency Inversion","marks":[{"type":"italic"}]},{"type":"text","text":")"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"polityka i szczegóły zależą od abstrakcji należącej do polityki"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Adapter","marks":[{"type":"link","attrs":{"href":"/pl/topics/adapter"}}]},{"type":"text","text":", "},{"type":"text","text":"Fabryka abstrakcyjna","marks":[{"type":"link","attrs":{"href":"/pl/topics/abstract-factory"}}]},{"type":"text","text":", "},{"type":"text","text":"architektura heksagonalna","marks":[{"type":"link","attrs":{"href":"/pl/topics/hexagonal-architecture"}}]}]}]}]}]},{"type":"diagram","attrs":{"kind":"mermaid","code":"flowchart LR\n  S[\"S – pojedyncza<br/>odpowiedzialność\"] --> DEC[\"Dekorator\"]\n  S --> OBS[\"Obserwator\"]\n  O[\"O – otwarte–zamknięte\"] --> STR[\"Strategia\"]\n  O --> DEC\n  O --> TM[\"Metoda szablonowa\"]\n  L[\"L – podstawienie Liskov\"] --> COMP[\"Kompozyt\"]\n  L --> PROXY[\"Pełnomocnik\"]\n  I[\"I – segregacja<br/>interfejsów\"] --> AD[\"Adapter\"]\n  I --> FAC[\"Fasada\"]\n  D[\"D – odwrócenie<br/>zależności\"] --> AD\n  D --> AF[\"Fabryka abstrakcyjna\"]\n  D --> HEX[\"Architektura heksagonalna\"]","caption":"Zasady SOLID i wzorce, które je realizują"}},{"type":"heading","attrs":{"level":2,"id":"s-zasada-pojedynczej-odpowiedzialnosci-srp"},"content":[{"type":"text","text":"S – zasada pojedynczej odpowiedzialności (SRP)"}]},{"type":"paragraph","content":[{"type":"text","text":"Klasyczne sformułowanie brzmi: klasa powinna mieć tylko jeden powód do zmiany. Martin w "},{"type":"text","text":"Clean Architecture","marks":[{"type":"italic"}]},{"type":"text","text":" doprecyzował, co znaczy „powód”: "},{"type":"text","text":"moduł powinien odpowiadać przed jednym i tylko jednym aktorem","marks":[{"type":"bold"}]},{"type":"text","text":" – osobą lub grupą, która poprosi o zmianę."}]},{"type":"paragraph","content":[{"type":"text","text":"W pierogarni klasa "},{"type":"text","text":"OrderDocuments","marks":[{"type":"code"}]},{"type":"text","text":" drukuje bilecik dla kuchni, generuje pozycje faktury i treść SMS-a. Kuchnia, księgowość i marketing to trzech aktorów. Gorzej: bilecik i faktura korzystają ze wspólnej metody "},{"type":"text","text":"Label","marks":[{"type":"code"}]},{"type":"text","text":". Księgowa poprosiła o format „2 szt.” – i następnego dnia kucharze dostali bileciki, na których „2 szt. ruskie” wyglądało jak nowa pozycja menu."}]},{"type":"codeGroup","attrs":{"title":"SRP – naruszenie i poprawka"},"content":[{"type":"codeBlock","attrs":{"language":"csharp","filename":"OrderDocuments.cs"},"content":[{"type":"text","text":"public sealed record OrderLine(string Dish, int Qty, decimal Price);\npublic sealed record Order(string Id, IReadOnlyList<OrderLine> Lines);\n\n// Violation: one class answers to three actors – the kitchen, accounting and marketing.\npublic sealed class OrderDocuments(Order order)\n{\n    public string KitchenTicket() => string.Join(\"\\n\", order.Lines.Select(Label));\n    public string InvoiceLines() => string.Join(\"\\n\", order.Lines.Select(l => $\"{Label(l)}  {l.Qty * l.Price:0.00}\"));\n    public string SmsText() => $\"Order {order.Id} is on its way!\";\n\n    // Shared helper: accounting changes it to \"2 pcs\" and the kitchen ticket changes too.\n    private static string Label(OrderLine l) => $\"{l.Qty}x {l.Dish}\";\n}\n\n// Fix: one class per actor – each changes for its own reason.\npublic static class KitchenTicket // owned by the kitchen\n{\n    public static string For(Order o) => string.Join(\"\\n\", o.Lines.Select(l => $\"{l.Qty}x {l.Dish}\"));\n}\n\npublic static class Invoice // owned by accounting\n{\n    public static string LinesFor(Order o) =>\n        string.Join(\"\\n\", o.Lines.Select(l => $\"{l.Dish}, {l.Qty} pcs, {l.Qty * l.Price:0.00} zł\"));\n}\n\npublic static class CustomerMessages // owned by marketing\n{\n    public static string OnTheWay(Order o) => $\"Order {o.Id} is on its way!\";\n}"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"order-documents.ts"},"content":[{"type":"text","text":"interface OrderLine { dish: string; qty: number; price: number } // price in grosze\ninterface Order { id: string; lines: OrderLine[] }\n\nconst zl = (grosze: number): string => (grosze / 100).toFixed(2);\n\n// Violation: one class answers to three actors – the kitchen, accounting and marketing.\nexport class OrderDocuments {\n  constructor(private readonly order: Order) {}\n  kitchenTicket(): string { return this.order.lines.map(label).join('\\n'); }\n  invoiceLines(): string { return this.order.lines.map((l) => `${label(l)}  ${zl(l.qty * l.price)}`).join('\\n'); }\n  smsText(): string { return `Order ${this.order.id} is on its way!`; }\n}\n\n// Shared helper: accounting changes it to \"2 pcs\" and the kitchen ticket changes too.\nconst label = (l: OrderLine): string => `${l.qty}x ${l.dish}`;\n\n// Fix: one module per actor (kitchen/ticket.ts, accounting/invoice.ts, marketing/sms.ts).\nexport const kitchenTicket = (o: Order): string =>\n  o.lines.map((l) => `${l.qty}x ${l.dish}`).join('\\n');\n\nexport const invoiceLines = (o: Order): string =>\n  o.lines.map((l) => `${l.dish}, ${l.qty} pcs, ${zl(l.qty * l.price)} zł`).join('\\n');\n\nexport const onTheWaySms = (o: Order): string => `Order ${o.id} is on its way!`;"}]},{"type":"codeBlock","attrs":{"language":"java","filename":"OrderDocuments.java"},"content":[{"type":"text","text":"import java.math.BigDecimal;\nimport java.util.List;\nimport java.util.stream.Collectors;\n\nrecord OrderLine(String dish, int qty, BigDecimal price) {\n    BigDecimal total() { return price.multiply(BigDecimal.valueOf(qty)); }\n}\n\nrecord Order(String id, List<OrderLine> lines) {}\n\n// Violation: one class answers to three actors – the kitchen, accounting and marketing.\nrecord OrderDocuments(Order order) {\n    String kitchenTicket() { return order.lines().stream().map(OrderDocuments::label).collect(Collectors.joining(\"\\n\")); }\n    String invoiceLines() { return order.lines().stream().map(l -> label(l) + \"  \" + l.total()).collect(Collectors.joining(\"\\n\")); }\n    String smsText() { return \"Order \" + order.id() + \" is on its way!\"; }\n\n    // Shared helper: accounting changes it to \"2 pcs\" and the kitchen ticket changes too.\n    private static String label(OrderLine l) { return l.qty() + \"x \" + l.dish(); }\n}\n\n// Fix: one class per actor – each changes for its own reason.\nfinal class KitchenTicket { // owned by the kitchen\n    static String forOrder(Order o) {\n        return o.lines().stream().map(l -> l.qty() + \"x \" + l.dish()).collect(Collectors.joining(\"\\n\"));\n    }\n}\n\nfinal class Invoice { // owned by accounting\n    static String linesFor(Order o) {\n        return o.lines().stream().map(l -> l.dish() + \", \" + l.qty() + \" pcs, \" + l.total() + \" zł\")\n                .collect(Collectors.joining(\"\\n\"));\n    }\n}\n\nfinal class CustomerMessages { // owned by marketing\n    static String onTheWay(Order o) { return \"Order \" + o.id() + \" is on its way!\"; }\n}"}]},{"type":"codeBlock","attrs":{"language":"go","filename":"documents.go"},"content":[{"type":"text","text":"package orders\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\ntype OrderLine struct {\n\tDish  string\n\tQty   int\n\tPrice int64 // grosze\n}\n\ntype Order struct {\n\tID    string\n\tLines []OrderLine\n}\n\n// Violation: one type answers to three actors – the kitchen, accounting and marketing.\ntype OrderDocuments struct{ order Order }\n\nfunc (d OrderDocuments) KitchenTicket() string { return joinLines(d.order, label) }\nfunc (d OrderDocuments) InvoiceLines() string {\n\treturn joinLines(d.order, func(l OrderLine) string { return fmt.Sprintf(\"%s  %s\", label(l), zl(l)) })\n}\nfunc (d OrderDocuments) SMSText() string { return fmt.Sprintf(\"Order %s is on its way!\", d.order.ID) }\n\n// Shared helper: accounting changes it to \"2 pcs\" and the kitchen ticket changes too.\nfunc label(l OrderLine) string { return fmt.Sprintf(\"%dx %s\", l.Qty, l.Dish) }\n\n// Fix: one package per actor (kitchen, accounting, marketing), shown here as functions.\nfunc KitchenTicket(o Order) string {\n\treturn joinLines(o, func(l OrderLine) string { return fmt.Sprintf(\"%dx %s\", l.Qty, l.Dish) })\n}\n\nfunc InvoiceLines(o Order) string {\n\treturn joinLines(o, func(l OrderLine) string { return fmt.Sprintf(\"%s, %d pcs, %s zł\", l.Dish, l.Qty, zl(l)) })\n}\n\nfunc OnTheWaySMS(o Order) string { return fmt.Sprintf(\"Order %s is on its way!\", o.ID) }\n\n// joinLines and zl are plumbing, not policy – sharing them is fine.\nfunc joinLines(o Order, format func(OrderLine) string) string {\n\tout := make([]string, len(o.Lines))\n\tfor i, l := range o.Lines {\n\t\tout[i] = format(l)\n\t}\n\treturn strings.Join(out, \"\\n\")\n}\n\nfunc zl(l OrderLine) string {\n\ttotal := int64(l.Qty) * l.Price\n\treturn fmt.Sprintf(\"%d.%02d\", total/100, total%100)\n}"}]},{"type":"codeBlock","attrs":{"language":"python","filename":"order_documents.py"},"content":[{"type":"text","text":"from dataclasses import dataclass\nfrom decimal import Decimal\n\n\n@dataclass(frozen=True)\nclass OrderLine:\n    dish: str\n    qty: int\n    price: Decimal\n\n\n@dataclass(frozen=True)\nclass Order:\n    id: str\n    lines: list[OrderLine]\n\n\n# Violation: one class answers to three actors – the kitchen, accounting and marketing.\nclass OrderDocuments:\n    def __init__(self, order: Order) -> None:\n        self._order = order\n\n    def kitchen_ticket(self) -> str:\n        return \"\\n\".join(self._label(line) for line in self._order.lines)\n\n    def invoice_lines(self) -> str:\n        return \"\\n\".join(f\"{self._label(line)}  {line.qty * line.price:.2f}\" for line in self._order.lines)\n\n    def sms_text(self) -> str:\n        return f\"Order {self._order.id} is on its way!\"\n\n    @staticmethod\n    def _label(line: OrderLine) -> str:\n        # Shared helper: accounting changes it to \"2 pcs\" and the kitchen ticket changes too.\n        return f\"{line.qty}x {line.dish}\"\n\n\n# Fix: one module per actor – kitchen.py, accounting.py, marketing.py.\ndef kitchen_ticket(order: Order) -> str:\n    return \"\\n\".join(f\"{line.qty}x {line.dish}\" for line in order.lines)\n\n\ndef invoice_lines(order: Order) -> str:\n    return \"\\n\".join(f\"{line.dish}, {line.qty} pcs, {line.qty * line.price:.2f} zł\" for line in order.lines)\n\n\ndef on_the_way_sms(order: Order) -> str:\n    return f\"Order {order.id} is on its way!\"\n\n\norder = Order(\"A-1042\", [OrderLine(\"ruskie\", 2, Decimal(\"21.90\"))])\nprint(kitchen_ticket(order), \"|\", invoice_lines(order))  # 2x ruskie | ruskie, 2 pcs, 43.80 zł"}]}]},{"type":"paragraph","content":[{"type":"text","text":"Po zmianie każda klasa należy do jednego aktora i zmienia się z jego powodu. Wspólne mogą zostać elementy techniczne – w wersji Go funkcja "},{"type":"text","text":"joinLines","marks":[{"type":"code"}]},{"type":"text","text":" to hydraulika, a nie polityka, więc dzielenie się nią niczego nie sprzęga."}]},{"type":"callout","attrs":{"variant":"info","title":"SRP to nie „jedna metoda”"},"content":[{"type":"paragraph","content":[{"type":"text","text":"Zasada „funkcja powinna robić jedną rzecz” z "},{"type":"text","text":"Clean Code","marks":[{"type":"italic"}]},{"type":"text","text":" dotyczy funkcji. SRP dotyczy modułów i ludzi. "},{"type":"text","text":"KitchenTicket","marks":[{"type":"code"}]},{"type":"text","text":" może mieć dziesięć metod – układ, skróty, alergeny, kolejność dań – dopóki wszystkie zmieniają się na prośbę kuchni."}]}]},{"type":"heading","attrs":{"level":2,"id":"o-zasada-otwarte-zamkniete-ocp"},"content":[{"type":"text","text":"O – zasada otwarte–zamknięte (OCP)"}]},{"type":"paragraph","content":[{"type":"text","text":"Bertrand Meyer pisał w 1988 roku, że moduły powinny być "},{"type":"text","text":"otwarte na rozszerzanie, ale zamknięte na modyfikacje","marks":[{"type":"bold"}]},{"type":"text","text":". Meyer myślał o dziedziczeniu; Martin przeniósł zasadę na abstrakcje i polimorfizm: nowe zachowanie dodajesz nową klasą lub funkcją, a sprawdzony kod, który z niego korzysta, zostaje nietknięty."}]},{"type":"paragraph","content":[{"type":"text","text":"Promocje w sklepie zaczęły się od jednej („–10%”), potem doszła darmowa dostawa, potem „druga porcja za pół ceny”. Każda oznaczała edycję tej samej instrukcji "},{"type":"text","text":"switch","marks":[{"type":"code"}]},{"type":"text","text":" i ponowne testowanie wszystkich gałęzi."}]},{"type":"codeGroup","attrs":{"title":"OCP – naruszenie i poprawka"},"content":[{"type":"codeBlock","attrs":{"language":"csharp","filename":"Promotions.cs"},"content":[{"type":"text","text":"public sealed record Cart(long Total, long DeliveryFee, long CheapestItem); // grosze\n\n// Violation: every new promotion means editing this switch and re-testing all of it.\npublic enum PromoKind { TenPercent, FreeDelivery, SecondHalfPrice }\n\npublic static class PromoCalculator\n{\n    public static long Discount(PromoKind kind, Cart cart) => kind switch\n    {\n        PromoKind.TenPercent => cart.Total / 10,\n        PromoKind.FreeDelivery => cart.DeliveryFee,\n        PromoKind.SecondHalfPrice => cart.CheapestItem / 2,\n        _ => throw new ArgumentOutOfRangeException(nameof(kind)),\n    };\n}\n\n// Fix: closed for modification, open for extension – a new promotion is a new class.\npublic interface IPromotion { long Discount(Cart cart); }\n\npublic sealed class PercentOff(int percent) : IPromotion\n{\n    public long Discount(Cart cart) => cart.Total * percent / 100;\n}\n\npublic sealed class FreeDelivery : IPromotion\n{\n    public long Discount(Cart cart) => cart.DeliveryFee;\n}\n\npublic sealed class SecondHalfPrice : IPromotion\n{\n    public long Discount(Cart cart) => cart.CheapestItem / 2;\n}\n\npublic sealed class Checkout(IEnumerable<IPromotion> promotions)\n{\n    public long Total(Cart cart) => cart.Total + cart.DeliveryFee - promotions.Sum(p => p.Discount(cart));\n}"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"promotions.ts"},"content":[{"type":"text","text":"interface Cart { total: number; deliveryFee: number; cheapestItem: number } // grosze\n\n// Violation: every new promotion means editing this switch and re-testing all of it.\ntype PromoKind = 'ten-percent' | 'free-delivery' | 'second-half-price';\n\nexport function discount(kind: PromoKind, cart: Cart): number {\n  switch (kind) {\n    case 'ten-percent': return Math.floor(cart.total / 10);\n    case 'free-delivery': return cart.deliveryFee;\n    case 'second-half-price': return Math.floor(cart.cheapestItem / 2);\n  }\n}\n\n// Fix: closed for modification, open for extension – a new promotion is a new function.\nexport type Promotion = (cart: Cart) => number;\n\nexport const percentOff = (percent: number): Promotion => (cart) => Math.floor((cart.total * percent) / 100);\nexport const freeDelivery: Promotion = (cart) => cart.deliveryFee;\nexport const secondHalfPrice: Promotion = (cart) => Math.floor(cart.cheapestItem / 2);\n\nexport function checkoutTotal(cart: Cart, promotions: readonly Promotion[]): number {\n  return cart.total + cart.deliveryFee - promotions.reduce((sum, promo) => sum + promo(cart), 0);\n}\n\nconsole.log(checkoutTotal({ total: 9_000, deliveryFee: 700, cheapestItem: 2_190 }, [percentOff(10), freeDelivery])); // 8100"}]},{"type":"codeBlock","attrs":{"language":"java","filename":"Promotions.java"},"content":[{"type":"text","text":"import java.util.List;\n\nrecord Cart(long total, long deliveryFee, long cheapestItem) {} // grosze\n\n// Violation: every new promotion means editing this switch and re-testing all of it.\nenum PromoKind { TEN_PERCENT, FREE_DELIVERY, SECOND_HALF_PRICE }\n\nfinal class PromoCalculator {\n    static long discount(PromoKind kind, Cart cart) {\n        return switch (kind) {\n            case TEN_PERCENT -> cart.total() / 10;\n            case FREE_DELIVERY -> cart.deliveryFee();\n            case SECOND_HALF_PRICE -> cart.cheapestItem() / 2;\n        };\n    }\n}\n\n// Fix: closed for modification, open for extension – a new promotion is a new class.\ninterface Promotion { long discount(Cart cart); }\n\nrecord PercentOff(int percent) implements Promotion {\n    public long discount(Cart cart) { return cart.total() * percent / 100; }\n}\n\nrecord FreeDelivery() implements Promotion {\n    public long discount(Cart cart) { return cart.deliveryFee(); }\n}\n\nrecord SecondHalfPrice() implements Promotion {\n    public long discount(Cart cart) { return cart.cheapestItem() / 2; }\n}\n\nrecord Checkout(List<Promotion> promotions) {\n    long total(Cart cart) {\n        return cart.total() + cart.deliveryFee() - promotions.stream().mapToLong(p -> p.discount(cart)).sum();\n    }\n}"}]},{"type":"codeBlock","attrs":{"language":"go","filename":"promotions.go"},"content":[{"type":"text","text":"package promotions\n\ntype Cart struct {\n\tTotal, DeliveryFee, CheapestItem int64 // grosze\n}\n\n// Violation: every new promotion means editing this switch and re-testing all of it.\ntype PromoKind int\n\nconst (\n\tTenPercent PromoKind = iota\n\tFreeDeliveryKind\n\tSecondHalfPriceKind\n)\n\nfunc Discount(kind PromoKind, cart Cart) int64 {\n\tswitch kind {\n\tcase TenPercent:\n\t\treturn cart.Total / 10\n\tcase FreeDeliveryKind:\n\t\treturn cart.DeliveryFee\n\tcase SecondHalfPriceKind:\n\t\treturn cart.CheapestItem / 2\n\t}\n\treturn 0\n}\n\n// Fix: closed for modification, open for extension – a new promotion is a new func or type.\ntype Promotion interface{ Discount(cart Cart) int64 }\n\n// PromotionFunc lets a plain function act as a Promotion, like http.HandlerFunc.\ntype PromotionFunc func(cart Cart) int64\n\nfunc (f PromotionFunc) Discount(cart Cart) int64 { return f(cart) }\n\nfunc PercentOff(percent int64) Promotion {\n\treturn PromotionFunc(func(c Cart) int64 { return c.Total * percent / 100 })\n}\n\nvar (\n\tFreeDelivery    = PromotionFunc(func(c Cart) int64 { return c.DeliveryFee })\n\tSecondHalfPrice = PromotionFunc(func(c Cart) int64 { return c.CheapestItem / 2 })\n)\n\nfunc CheckoutTotal(cart Cart, promotions ...Promotion) int64 {\n\ttotal := cart.Total + cart.DeliveryFee\n\tfor _, p := range promotions {\n\t\ttotal -= p.Discount(cart)\n\t}\n\treturn total\n}"}]},{"type":"codeBlock","attrs":{"language":"python","filename":"promotions.py"},"content":[{"type":"text","text":"from collections.abc import Callable, Iterable\nfrom dataclasses import dataclass\nfrom enum import Enum, auto\n\n\n@dataclass(frozen=True)\nclass Cart:\n    total: int  # grosze\n    delivery_fee: int\n    cheapest_item: int\n\n\n# Violation: every new promotion means editing this function and re-testing all of it.\nclass PromoKind(Enum):\n    TEN_PERCENT = auto()\n    FREE_DELIVERY = auto()\n    SECOND_HALF_PRICE = auto()\n\n\ndef discount(kind: PromoKind, cart: Cart) -> int:\n    match kind:\n        case PromoKind.TEN_PERCENT:\n            return cart.total // 10\n        case PromoKind.FREE_DELIVERY:\n            return cart.delivery_fee\n        case PromoKind.SECOND_HALF_PRICE:\n            return cart.cheapest_item // 2\n\n\n# Fix: closed for modification, open for extension – a new promotion is a new function.\nPromotion = Callable[[Cart], int]\n\n\ndef percent_off(percent: int) -> Promotion:\n    return lambda cart: cart.total * percent // 100\n\n\ndef free_delivery(cart: Cart) -> int:\n    return cart.delivery_fee\n\n\ndef second_half_price(cart: Cart) -> int:\n    return cart.cheapest_item // 2\n\n\ndef checkout_total(cart: Cart, promotions: Iterable[Promotion]) -> int:\n    return cart.total + cart.delivery_fee - sum(promo(cart) for promo in promotions)\n\n\nprint(checkout_total(Cart(9000, 700, 2190), [percent_off(10), free_delivery]))  # 8100"}]}]}]},"toc":[{"id":"skad-sie-wzielo-solid","text":"Skąd się wzięło SOLID","level":2,"locked":false},{"id":"s-zasada-pojedynczej-odpowiedzialnosci-srp","text":"S – zasada pojedynczej odpowiedzialności (SRP)","level":2,"locked":false},{"id":"o-zasada-otwarte-zamkniete-ocp","text":"O – zasada otwarte–zamknięte (OCP)","level":2,"locked":false},{"id":"l-zasada-podstawienia-liskov-lsp","text":"L – zasada podstawienia Liskov (LSP)","level":2,"locked":true},{"id":"i-zasada-segregacji-interfejsow-isp","text":"I – zasada segregacji interfejsów (ISP)","level":2,"locked":true},{"id":"d-zasada-odwrocenia-zaleznosci-dip","text":"D – zasada odwrócenia zależności (DIP)","level":2,"locked":true},{"id":"najczestsze-bledne-interpretacje","text":"Najczęstsze błędne interpretacje","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":57,"visibleBlocks":18,"resources":[{"id":"6b0857c33c96f2d34d0b4687","type":"book","provider":"openlibrary","url":"https://openlibrary.org/works/OL7952934W","embedUrl":null,"title":"Agile Software Development, Principles, Patterns, and Practices","description":"","author":"Robert C. Martin","thumbnailUrl":"https://covers.openlibrary.org/b/id/91081-L.jpg","durationSec":null,"lang":"en","topics":[],"techs":["general"],"tags":["book"],"price":"paid","featured":false,"featuredOrder":0,"packageName":null,"source":"openlibrary","publishedAt":"2002-01-01T00:00:00.000Z","popularity":53,"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":"6b0857b53c96f2d34d0b38d3","type":"article","provider":"web","url":"https://khalilstemmler.com/articles/solid-principles/solid-typescript","embedUrl":null,"title":"Solid Principles: A Software Developer’s Framework to Robust, Maintainable Code","description":"The SOLID principles are a set of software design principles that teach us how we can structure our functions and classes to be as robust, maintainable and flexible as possible.","author":"Khalil Stemmler","thumbnailUrl":"https://khalilstemmler.com/img/blog/solid/solid.png","durationSec":null,"lang":"en","topics":["solid"],"techs":["general"],"tags":["hacker-news"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"hn","publishedAt":"2019-05-19T20:54:35.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":"6b0857c53c96f2d34d0b4885","type":"video","provider":"youtube","url":"https://www.youtube.com/watch?v=AEnePs2Evg0","embedUrl":"https://www.youtube-nocookie.com/embed/AEnePs2Evg0","title":"Single Responsibility Principle (SOLID) | A single reason to change — Code Walks 006","description":"The single responsibility principle is actually one of the more easily understood principles of the SOLID principles. Yet the expression \"doing a single thing\" makes many of us endlessly ponder — what is in fact a single thing? Let's talk about that. TIMESTAMPS BELOW. 0:30 \"A single reason to…","author":"Christopher Okhravi","thumbnailUrl":"https://i.ytimg.com/vi/AEnePs2Evg0/hqdefault.jpg","durationSec":null,"lang":"en","topics":["solid"],"techs":["general"],"tags":[],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"youtube-rss","publishedAt":"2016-07-16T09:26:19.000Z","popularity":72,"verifiedAt":"2026-11-26T10:57:18.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:07.481Z","updatedAt":"2026-11-26T16:01:07.481Z"},{"id":"6b0857c23c96f2d34d0b4527","type":"article","provider":"web","url":"https://blog.ndepend.com/solid-design-the-liskov-substitution-principle","embedUrl":null,"title":"SOLID Design in C#: The Liskov Substitution Principle (LSP) - NDepend Blog","description":"The Liskov Substitution Principle states that objects of a base class shall be replaced with objects of its subclasses without causing errors","author":"NDepend Blog","thumbnailUrl":"https://blog.ndepend.com/wp-content/uploads/SOLID-Design-in-C-The-Liskov-Substitution-Principle.png","durationSec":null,"lang":"en","topics":["solid"],"techs":["dotnet"],"tags":[],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"manual","publishedAt":"2026-05-25T01:01:41.000Z","popularity":50,"verifiedAt":"2026-11-26T11:30:29.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:04.995Z","updatedAt":"2026-11-26T16:01:04.995Z"},{"id":"6b0857c53c96f2d34d0b4879","type":"video","provider":"youtube","url":"https://www.youtube.com/watch?v=S9awxA1wNNY","embedUrl":"https://www.youtube-nocookie.com/embed/S9awxA1wNNY","title":"Dependency Inversion - how, what, why? (examples in C#) | Code Walks 004","description":"CODE EXAMPLES FROM 4:00. Dependency inversion is the D in the SOLID design principles. But what does it really mean? Let me give you a no-nonsense explanation of what it is, why it is so incredibly important and how you go about using it. Subscribe for more programming knowledge. Suggestions for…","author":"Christopher Okhravi","thumbnailUrl":"https://i.ytimg.com/vi/S9awxA1wNNY/hqdefault.jpg","durationSec":null,"lang":"en","topics":["solid"],"techs":["dotnet"],"tags":[],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"youtube-rss","publishedAt":"2016-07-16T09:26:18.000Z","popularity":72,"verifiedAt":"2026-11-26T10:57:19.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:07.481Z","updatedAt":"2026-11-26T16:01:07.481Z"},{"id":"6b0857bd3c96f2d34d0b41ad","type":"podcast","provider":"apple-podcasts","url":"https://podcasts.apple.com/us/podcast/solid-principles-with-uncle-bob-robert-c-martin/id117488860?i=1000405695843","embedUrl":"https://embed.podcasts.apple.com/us/podcast/id117488860?i=1000405695843","title":"SOLID Principles with Uncle Bob - Robert C. Martin","description":"Scott sits down with Robert C. Martin as Uncle Bob helps Scott understand the SOLID Principles of Object Oriented Design.","author":"Hanselminutes with Scott Hanselman","thumbnailUrl":"https://is1-ssl.mzstatic.com/image/thumb/Podcasts115/v4/cd/66/2c/cd662c27-010a-73d1-25c9-8d6f1eefbe42/mza_5085684663945528791.jpg/600x600bb.jpg","durationSec":2711,"lang":"en","topics":["solid"],"techs":["general"],"tags":["podcast"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"itunes","publishedAt":"2009-01-05T20:08:16.000Z","popularity":26,"verifiedAt":"2026-11-26T10:59:18.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:59.965Z","updatedAt":"2026-11-26T16:00:59.965Z"}],"challenges":[{"id":"6b0857af5a2625e44ecaad13","slug":"design-patterns-basics-quiz","title":"Wzorce projektowe – podstawy","summary":"Sześć pytań o klasyczne wzorce GoF: grupy, przeznaczenie i różnice.","servedLang":"pl","availableLangs":["pl","en"],"kind":"quiz","category":null,"status":"published","difficulty":"easy","topics":["builder","adapter","strategy","decorator","composite","facade","observer"],"techs":["general"],"tags":["quiz","gof","basics"],"languages":[],"questionCount":6,"xp":10,"stats":{"attempts":1,"solves":1,"solutions":0,"comments":0},"solveRate":100,"publishedAt":"2026-11-26T16:00:47.960Z"},{"id":"6b093dddbd4755deb67ee061","slug":"debounce-throttle","title":"Debounce i throttle","summary":"Dwie klasyczne funkcje wyższego rzędu z frontendu – debounce (wywołaj po ciszy) i throttle (najwyżej raz na okres) – z cancel, flush, zachowaniem this i wstrzykiwanymi timerami.","servedLang":"pl","availableLangs":["pl","en"],"kind":"code","category":"algorithms","status":"published","difficulty":"medium","topics":["decorator"],"techs":["typescript","javascript"],"tags":["javascript","closures","timers","event-loop","higher-order-functions"],"languages":["typescript","javascript"],"questionCount":null,"xp":20,"stats":{"attempts":0,"solves":0,"solutions":0,"comments":0},"solveRate":null,"publishedAt":"2026-11-27T08:22:53.681Z"},{"id":"6b0857af5a2625e44ecaad0d","slug":"discount-strategy","title":"Strategia rabatów","summary":"Wymienne algorytmy rabatowe w koszyku: procentowy, progowy i „najlepszy z”, podmieniane w trakcie działania.","servedLang":"pl","availableLangs":["pl","en"],"kind":"code","category":null,"status":"published","difficulty":"medium","topics":["strategy"],"techs":["python","typescript"],"tags":["strategy","e-commerce","behavioral"],"languages":["python","typescript"],"questionCount":null,"xp":20,"stats":{"attempts":1,"solves":1,"solutions":1,"comments":0},"solveRate":100,"publishedAt":"2026-11-26T16:00:47.764Z"}],"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":false},{"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":true}]}],"prev":{"slug":"law-of-demeter","title":"Prawo Demeter: rozmawiaj tylko z przyjaciółmi"},"next":null,"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}]}}