{"id":"6b09a4bfff996234422a2756","slug":"solid","title":"SOLID: five object-oriented design principles without the myths","summary":"The SOLID principles through Halina's pierogi place: SRP, OCP, LSP, ISP and DIP – each with a violation and a fix in C#, TypeScript, Java, Go and Python, plus diagrams, the patterns that implement them and the most common misreadings.","servedLang":"en","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":33,"stats":{"views":1,"likes":0,"bookmarks":0,"comments":0},"publishedAt":"2026-11-27T15:41:51.919Z","updatedAt":"2026-11-27T17:30:51.326Z","requestedLang":"en","theme":{"hero":"classic","heroMedia":null,"accent":"amber","background":"dots","weaveResources":true,"toc":"right"},"seoDescription":"SOLID in practice: single responsibility, open/closed, Liskov substitution, interface segregation and dependency inversion – violations and fixes in C#, TypeScript, Java, Go and Python, patterns (Strategy, Decorator, Adapter) and myths such as SRP meaning “one method”.","wordCount":6453,"doc":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"The code of Halina's pierogi shop is a few years old now. The kitchen, accounting and marketing all request changes to the same classes, every new promotion is another "},{"type":"text","text":"case","marks":[{"type":"code"}]},{"type":"text","text":", and the kitchen display test needs a fake with six methods. "},{"type":"text","text":"SOLID","marks":[{"type":"bold"}]},{"type":"text","text":" is a set of five principles collected by Robert C. Martin that help such code change without a domino effect. They are not laws of physics – they are heuristics that work best when you understand which problem each of them solves."}]},{"type":"callout","attrs":{"variant":"tip","title":"In short"},"content":[{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Each principle answers a different question: who asks for changes (SRP), how to add variants (OCP), when a subtype is substitutable (LSP), how much a client needs to know (ISP), who depends on whom (DIP)."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Many GoF patterns are ready-made ways to implement SOLID: Strategy and Decorator for OCP, Adapter for DIP and ISP."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Most mistakes come from reading the names literally: SRP is not \"one method\", and DIP is not \"a DI container\"."}]}]}]}]},{"type":"stats","attrs":{"items":[{"value":"5","label":"principles","hint":"SRP, OCP, LSP, ISP, DIP"},{"value":"1987","label":"the oldest of them","hint":"Barbara Liskov and the substitution principle"},{"value":"c. 2004","label":"the SOLID acronym","hint":"coined by Michael Feathers"}]}},{"type":"heading","attrs":{"level":2,"id":"where-solid-comes-from"},"content":[{"type":"text","text":"Where SOLID comes from"}]},{"type":"paragraph","content":[{"type":"text","text":"The principles were born separately and only later ended up in one bag:"}]},{"type":"timeline","attrs":{"items":[{"date":"1987","title":"Barbara Liskov","text":"The \"Data Abstraction and Hierarchy\" keynote at OOPSLA – the substitution principle."},{"date":"1988","title":"Bertrand Meyer","text":"\"Object-Oriented Software Construction\" – modules open for extension, closed for modification."},{"date":"1996","title":"Robert C. Martin","text":"A series of C++ Report articles: open/closed, Liskov substitution, dependency inversion, interface segregation."},{"date":"2000","title":"\"Design Principles and Design Patterns\"","text":"Martin gathers the class design principles in a single paper."},{"date":"c. 2004","title":"Michael Feathers","text":"Arranges the initials into the SOLID acronym."},{"date":"2017","title":"\"Clean Architecture\"","text":"Martin restates SRP: a module is responsible to one actor."}]}},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Letter"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Principle"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"In one sentence"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Patterns that implement it"}]}]}]},{"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":"Single Responsibility"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"a module is responsible to one actor"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Decorator","marks":[{"type":"link","attrs":{"href":"/en/topics/decorator"}}]},{"type":"text","text":", "},{"type":"text","text":"Observer","marks":[{"type":"link","attrs":{"href":"/en/topics/observer"}}]},{"type":"text","text":", "},{"type":"text","text":"Command","marks":[{"type":"link","attrs":{"href":"/en/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":"Open/Closed"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"you add behaviour with new code, not by editing old code"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Strategy","marks":[{"type":"link","attrs":{"href":"/en/topics/strategy"}}]},{"type":"text","text":", "},{"type":"text","text":"Decorator","marks":[{"type":"link","attrs":{"href":"/en/topics/decorator"}}]},{"type":"text","text":", "},{"type":"text","text":"Template Method","marks":[{"type":"link","attrs":{"href":"/en/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":"Liskov Substitution"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"a subtype honours the base type's contract"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Composite","marks":[{"type":"link","attrs":{"href":"/en/topics/composite"}}]},{"type":"text","text":", "},{"type":"text","text":"Proxy","marks":[{"type":"link","attrs":{"href":"/en/topics/proxy"}}]},{"type":"text","text":", "},{"type":"text","text":"State","marks":[{"type":"link","attrs":{"href":"/en/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":"Interface Segregation"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"a client depends only on the methods it uses"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Adapter","marks":[{"type":"link","attrs":{"href":"/en/topics/adapter"}}]},{"type":"text","text":", "},{"type":"text","text":"Facade","marks":[{"type":"link","attrs":{"href":"/en/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":"Dependency Inversion"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"policy and details depend on an abstraction owned by the policy"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Adapter","marks":[{"type":"link","attrs":{"href":"/en/topics/adapter"}}]},{"type":"text","text":", "},{"type":"text","text":"Abstract Factory","marks":[{"type":"link","attrs":{"href":"/en/topics/abstract-factory"}}]},{"type":"text","text":", "},{"type":"text","text":"hexagonal architecture","marks":[{"type":"link","attrs":{"href":"/en/topics/hexagonal-architecture"}}]}]}]}]}]},{"type":"diagram","attrs":{"kind":"mermaid","code":"flowchart LR\n  S[\"S – single<br/>responsibility\"] --> DEC[\"Decorator\"]\n  S --> OBS[\"Observer\"]\n  O[\"O – open/closed\"] --> STR[\"Strategy\"]\n  O --> DEC\n  O --> TM[\"Template Method\"]\n  L[\"L – Liskov substitution\"] --> COMP[\"Composite\"]\n  L --> PROXY[\"Proxy\"]\n  I[\"I – interface<br/>segregation\"] --> AD[\"Adapter\"]\n  I --> FAC[\"Facade\"]\n  D[\"D – dependency<br/>inversion\"] --> AD\n  D --> AF[\"Abstract Factory\"]\n  D --> HEX[\"Hexagonal architecture\"]","caption":"The SOLID principles and the patterns that implement them"}},{"type":"heading","attrs":{"level":2,"id":"s-the-single-responsibility-principle-srp"},"content":[{"type":"text","text":"S – the Single Responsibility Principle (SRP)"}]},{"type":"paragraph","content":[{"type":"text","text":"The classic wording is: a class should have only one reason to change. In "},{"type":"text","text":"Clean Architecture","marks":[{"type":"italic"}]},{"type":"text","text":", Martin clarified what a \"reason\" is: "},{"type":"text","text":"a module should be responsible to one, and only one, actor","marks":[{"type":"bold"}]},{"type":"text","text":" – a person or group who will ask for the change."}]},{"type":"paragraph","content":[{"type":"text","text":"In the pierogi place, the "},{"type":"text","text":"OrderDocuments","marks":[{"type":"code"}]},{"type":"text","text":" class prints the kitchen ticket, generates invoice lines and composes the SMS text. The kitchen, accounting and marketing are three actors. Worse: the ticket and the invoice share a "},{"type":"text","text":"Label","marks":[{"type":"code"}]},{"type":"text","text":" method. The accountant asked for the \"2 pcs\" format – and the next day the cooks got tickets where \"2 pcs ruskie\" looked like a new menu item."}]},{"type":"codeGroup","attrs":{"title":"SRP – violation and fix"},"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":"After the change, every class belongs to one actor and changes for that actor's reasons. Technical pieces can stay shared – in the Go version, "},{"type":"text","text":"joinLines","marks":[{"type":"code"}]},{"type":"text","text":" is plumbing, not policy, so sharing it couples nothing."}]},{"type":"callout","attrs":{"variant":"info","title":"SRP is not \"one method\""},"content":[{"type":"paragraph","content":[{"type":"text","text":"\"A function should do one thing\" from "},{"type":"text","text":"Clean Code","marks":[{"type":"italic"}]},{"type":"text","text":" is about functions. SRP is about modules and people. "},{"type":"text","text":"KitchenTicket","marks":[{"type":"code"}]},{"type":"text","text":" can have ten methods – layout, abbreviations, allergens, course order – as long as they all change at the kitchen's request."}]}]},{"type":"heading","attrs":{"level":2,"id":"o-the-open-closed-principle-ocp"},"content":[{"type":"text","text":"O – the Open/Closed Principle (OCP)"}]},{"type":"paragraph","content":[{"type":"text","text":"In 1988 Bertrand Meyer wrote that modules should be "},{"type":"text","text":"open for extension but closed for modification","marks":[{"type":"bold"}]},{"type":"text","text":". Meyer had inheritance in mind; Martin moved the principle to abstractions and polymorphism: you add new behaviour with a new class or function, and the proven code that uses it stays untouched."}]},{"type":"paragraph","content":[{"type":"text","text":"The shop's promotions started with one (\"–10%\"), then free delivery came along, then \"second portion half price\". Each one meant editing the same "},{"type":"text","text":"switch","marks":[{"type":"code"}]},{"type":"text","text":" and re-testing every branch."}]},{"type":"codeGroup","attrs":{"title":"OCP – violation and fix"},"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":"where-solid-comes-from","text":"Where SOLID comes from","level":2,"locked":false},{"id":"s-the-single-responsibility-principle-srp","text":"S – the Single Responsibility Principle (SRP)","level":2,"locked":false},{"id":"o-the-open-closed-principle-ocp","text":"O – the Open/Closed Principle (OCP)","level":2,"locked":false},{"id":"l-the-liskov-substitution-principle-lsp","text":"L – the Liskov Substitution Principle (LSP)","level":2,"locked":true},{"id":"i-the-interface-segregation-principle-isp","text":"I – the Interface Segregation Principle (ISP)","level":2,"locked":true},{"id":"d-the-dependency-inversion-principle-dip","text":"D – the Dependency Inversion Principle (DIP)","level":2,"locked":true},{"id":"the-most-common-misreadings","text":"The most common misreadings","level":2,"locked":true},{"id":"when-to-use-it-and-when-not-to","text":"When to use it and when not to","level":2,"locked":true},{"id":"in-practice","text":"In practice","level":2,"locked":true},{"id":"related-topics","text":"Related topics","level":2,"locked":true},{"id":"test-yourself","text":"Test yourself","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":"Design patterns – basics","summary":"Six questions about classic GoF patterns: groups, intent and differences.","servedLang":"en","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 and throttle","summary":"Two classic frontend higher-order functions – debounce (call after silence) and throttle (at most once per period) – with cancel, flush, preserved this and injected timers.","servedLang":"en","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":"Discount strategy","summary":"Interchangeable discount algorithms in a checkout: percentage, threshold and \"best of\", swapped at runtime.","servedLang":"en","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":"Design principles","items":[{"slug":"kiss","title":"KISS: the simplest working solution usually wins","current":false},{"slug":"dry","title":"DRY: one piece of knowledge, one place – and when duplication is cheaper","current":false},{"slug":"yagni","title":"YAGNI: don't build ahead – what a feature nobody ordered really costs","current":false},{"slug":"law-of-demeter","title":"The Law of Demeter: talk only to your friends","current":false},{"slug":"solid","title":"SOLID: five object-oriented design principles without the myths","current":true}]}],"prev":{"slug":"law-of-demeter","title":"The Law of Demeter: talk only to your friends"},"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":"Authority","articles":90},{"key":"dotnet","title":".NET","level":5,"levelLabel":"Authority","articles":61},{"key":"python","title":"Python","level":5,"levelLabel":"Authority","articles":59},{"key":"java","title":"Java","level":5,"levelLabel":"Authority","articles":46}]}}