SOLID: five object-oriented design principles without the myths
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.
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 case, and the kitchen display test needs a fake with six methods. SOLID 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.
- 5
- principles – SRP, OCP, LSP, ISP, DIP
- 1987
- the oldest of them – Barbara Liskov and the substitution principle
- c. 2004
- the SOLID acronym – coined by Michael Feathers
Where SOLID comes from
The principles were born separately and only later ended up in one bag:
- 1987 Barbara Liskov – The "Data Abstraction and Hierarchy" keynote at OOPSLA – the substitution principle.
- 1988 Bertrand Meyer – "Object-Oriented Software Construction" – modules open for extension, closed for modification.
- 1996 Robert C. Martin – A series of C++ Report articles: open/closed, Liskov substitution, dependency inversion, interface segregation.
- 2000 "Design Principles and Design Patterns" – Martin gathers the class design principles in a single paper.
- c. 2004 Michael Feathers – Arranges the initials into the SOLID acronym.
- 2017 "Clean Architecture" – Martin restates SRP: a module is responsible to one actor.
| Letter | Principle | In one sentence | Patterns that implement it |
|---|---|---|---|
| S | Single Responsibility | a module is responsible to one actor | Decorator, Observer, Command |
| O | Open/Closed | you add behaviour with new code, not by editing old code | Strategy, Decorator, Template Method |
| L | Liskov Substitution | a subtype honours the base type's contract | Composite, Proxy, State |
| I | Interface Segregation | a client depends only on the methods it uses | Adapter, Facade |
| D | Dependency Inversion | policy and details depend on an abstraction owned by the policy | Adapter, Abstract Factory, hexagonal architecture |
S – the Single Responsibility Principle (SRP)
The classic wording is: a class should have only one reason to change. In Clean Architecture, Martin clarified what a "reason" is: a module should be responsible to one, and only one, actor – a person or group who will ask for the change.
In the pierogi place, the OrderDocuments 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 Label 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.
SRP – violation and fix
public sealed record OrderLine(string Dish, int Qty, decimal Price);
public sealed record Order(string Id, IReadOnlyList<OrderLine> Lines);
// Violation: one class answers to three actors – the kitchen, accounting and marketing.
public sealed class OrderDocuments(Order order)
{
public string KitchenTicket() => string.Join("\n", order.Lines.Select(Label));
public string InvoiceLines() => string.Join("\n", order.Lines.Select(l => $"{Label(l)} {l.Qty * l.Price:0.00}"));
public string SmsText() => $"Order {order.Id} is on its way!";
// Shared helper: accounting changes it to "2 pcs" and the kitchen ticket changes too.
private static string Label(OrderLine l) => $"{l.Qty}x {l.Dish}";
}
// Fix: one class per actor – each changes for its own reason.
public static class KitchenTicket // owned by the kitchen
{
public static string For(Order o) => string.Join("\n", o.Lines.Select(l => $"{l.Qty}x {l.Dish}"));
}
public static class Invoice // owned by accounting
{
public static string LinesFor(Order o) =>
string.Join("\n", o.Lines.Select(l => $"{l.Dish}, {l.Qty} pcs, {l.Qty * l.Price:0.00} zł"));
}
public static class CustomerMessages // owned by marketing
{
public static string OnTheWay(Order o) => $"Order {o.Id} is on its way!";
}interface OrderLine { dish: string; qty: number; price: number } // price in grosze
interface Order { id: string; lines: OrderLine[] }
const zl = (grosze: number): string => (grosze / 100).toFixed(2);
// Violation: one class answers to three actors – the kitchen, accounting and marketing.
export class OrderDocuments {
constructor(private readonly order: Order) {}
kitchenTicket(): string { return this.order.lines.map(label).join('\n'); }
invoiceLines(): string { return this.order.lines.map((l) => `${label(l)} ${zl(l.qty * l.price)}`).join('\n'); }
smsText(): string { return `Order ${this.order.id} is on its way!`; }
}
// Shared helper: accounting changes it to "2 pcs" and the kitchen ticket changes too.
const label = (l: OrderLine): string => `${l.qty}x ${l.dish}`;
// Fix: one module per actor (kitchen/ticket.ts, accounting/invoice.ts, marketing/sms.ts).
export const kitchenTicket = (o: Order): string =>
o.lines.map((l) => `${l.qty}x ${l.dish}`).join('\n');
export const invoiceLines = (o: Order): string =>
o.lines.map((l) => `${l.dish}, ${l.qty} pcs, ${zl(l.qty * l.price)} zł`).join('\n');
export const onTheWaySms = (o: Order): string => `Order ${o.id} is on its way!`;import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;
record OrderLine(String dish, int qty, BigDecimal price) {
BigDecimal total() { return price.multiply(BigDecimal.valueOf(qty)); }
}
record Order(String id, List<OrderLine> lines) {}
// Violation: one class answers to three actors – the kitchen, accounting and marketing.
record OrderDocuments(Order order) {
String kitchenTicket() { return order.lines().stream().map(OrderDocuments::label).collect(Collectors.joining("\n")); }
String invoiceLines() { return order.lines().stream().map(l -> label(l) + " " + l.total()).collect(Collectors.joining("\n")); }
String smsText() { return "Order " + order.id() + " is on its way!"; }
// Shared helper: accounting changes it to "2 pcs" and the kitchen ticket changes too.
private static String label(OrderLine l) { return l.qty() + "x " + l.dish(); }
}
// Fix: one class per actor – each changes for its own reason.
final class KitchenTicket { // owned by the kitchen
static String forOrder(Order o) {
return o.lines().stream().map(l -> l.qty() + "x " + l.dish()).collect(Collectors.joining("\n"));
}
}
final class Invoice { // owned by accounting
static String linesFor(Order o) {
return o.lines().stream().map(l -> l.dish() + ", " + l.qty() + " pcs, " + l.total() + " zł")
.collect(Collectors.joining("\n"));
}
}
final class CustomerMessages { // owned by marketing
static String onTheWay(Order o) { return "Order " + o.id() + " is on its way!"; }
}package orders
import (
"fmt"
"strings"
)
type OrderLine struct {
Dish string
Qty int
Price int64 // grosze
}
type Order struct {
ID string
Lines []OrderLine
}
// Violation: one type answers to three actors – the kitchen, accounting and marketing.
type OrderDocuments struct{ order Order }
func (d OrderDocuments) KitchenTicket() string { return joinLines(d.order, label) }
func (d OrderDocuments) InvoiceLines() string {
return joinLines(d.order, func(l OrderLine) string { return fmt.Sprintf("%s %s", label(l), zl(l)) })
}
func (d OrderDocuments) SMSText() string { return fmt.Sprintf("Order %s is on its way!", d.order.ID) }
// Shared helper: accounting changes it to "2 pcs" and the kitchen ticket changes too.
func label(l OrderLine) string { return fmt.Sprintf("%dx %s", l.Qty, l.Dish) }
// Fix: one package per actor (kitchen, accounting, marketing), shown here as functions.
func KitchenTicket(o Order) string {
return joinLines(o, func(l OrderLine) string { return fmt.Sprintf("%dx %s", l.Qty, l.Dish) })
}
func InvoiceLines(o Order) string {
return joinLines(o, func(l OrderLine) string { return fmt.Sprintf("%s, %d pcs, %s zł", l.Dish, l.Qty, zl(l)) })
}
func OnTheWaySMS(o Order) string { return fmt.Sprintf("Order %s is on its way!", o.ID) }
// joinLines and zl are plumbing, not policy – sharing them is fine.
func joinLines(o Order, format func(OrderLine) string) string {
out := make([]string, len(o.Lines))
for i, l := range o.Lines {
out[i] = format(l)
}
return strings.Join(out, "\n")
}
func zl(l OrderLine) string {
total := int64(l.Qty) * l.Price
return fmt.Sprintf("%d.%02d", total/100, total%100)
}from dataclasses import dataclass
from decimal import Decimal
@dataclass(frozen=True)
class OrderLine:
dish: str
qty: int
price: Decimal
@dataclass(frozen=True)
class Order:
id: str
lines: list[OrderLine]
# Violation: one class answers to three actors – the kitchen, accounting and marketing.
class OrderDocuments:
def __init__(self, order: Order) -> None:
self._order = order
def kitchen_ticket(self) -> str:
return "\n".join(self._label(line) for line in self._order.lines)
def invoice_lines(self) -> str:
return "\n".join(f"{self._label(line)} {line.qty * line.price:.2f}" for line in self._order.lines)
def sms_text(self) -> str:
return f"Order {self._order.id} is on its way!"
@staticmethod
def _label(line: OrderLine) -> str:
# Shared helper: accounting changes it to "2 pcs" and the kitchen ticket changes too.
return f"{line.qty}x {line.dish}"
# Fix: one module per actor – kitchen.py, accounting.py, marketing.py.
def kitchen_ticket(order: Order) -> str:
return "\n".join(f"{line.qty}x {line.dish}" for line in order.lines)
def invoice_lines(order: Order) -> str:
return "\n".join(f"{line.dish}, {line.qty} pcs, {line.qty * line.price:.2f} zł" for line in order.lines)
def on_the_way_sms(order: Order) -> str:
return f"Order {order.id} is on its way!"
order = Order("A-1042", [OrderLine("ruskie", 2, Decimal("21.90"))])
print(kitchen_ticket(order), "|", invoice_lines(order)) # 2x ruskie | ruskie, 2 pcs, 43.80 zł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, joinLines is plumbing, not policy, so sharing it couples nothing.
O – the Open/Closed Principle (OCP)
In 1988 Bertrand Meyer wrote that modules should be open for extension but closed for modification. 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.
The shop's promotions started with one ("–10%"), then free delivery came along, then "second portion half price". Each one meant editing the same switch and re-testing every branch.
OCP – violation and fix
public sealed record Cart(long Total, long DeliveryFee, long CheapestItem); // grosze
// Violation: every new promotion means editing this switch and re-testing all of it.
public enum PromoKind { TenPercent, FreeDelivery, SecondHalfPrice }
public static class PromoCalculator
{
public static long Discount(PromoKind kind, Cart cart) => kind switch
{
PromoKind.TenPercent => cart.Total / 10,
PromoKind.FreeDelivery => cart.DeliveryFee,
PromoKind.SecondHalfPrice => cart.CheapestItem / 2,
_ => throw new ArgumentOutOfRangeException(nameof(kind)),
};
}
// Fix: closed for modification, open for extension – a new promotion is a new class.
public interface IPromotion { long Discount(Cart cart); }
public sealed class PercentOff(int percent) : IPromotion
{
public long Discount(Cart cart) => cart.Total * percent / 100;
}
public sealed class FreeDelivery : IPromotion
{
public long Discount(Cart cart) => cart.DeliveryFee;
}
public sealed class SecondHalfPrice : IPromotion
{
public long Discount(Cart cart) => cart.CheapestItem / 2;
}
public sealed class Checkout(IEnumerable<IPromotion> promotions)
{
public long Total(Cart cart) => cart.Total + cart.DeliveryFee - promotions.Sum(p => p.Discount(cart));
}interface Cart { total: number; deliveryFee: number; cheapestItem: number } // grosze
// Violation: every new promotion means editing this switch and re-testing all of it.
type PromoKind = 'ten-percent' | 'free-delivery' | 'second-half-price';
export function discount(kind: PromoKind, cart: Cart): number {
switch (kind) {
case 'ten-percent': return Math.floor(cart.total / 10);
case 'free-delivery': return cart.deliveryFee;
case 'second-half-price': return Math.floor(cart.cheapestItem / 2);
}
}
// Fix: closed for modification, open for extension – a new promotion is a new function.
export type Promotion = (cart: Cart) => number;
export const percentOff = (percent: number): Promotion => (cart) => Math.floor((cart.total * percent) / 100);
export const freeDelivery: Promotion = (cart) => cart.deliveryFee;
export const secondHalfPrice: Promotion = (cart) => Math.floor(cart.cheapestItem / 2);
export function checkoutTotal(cart: Cart, promotions: readonly Promotion[]): number {
return cart.total + cart.deliveryFee - promotions.reduce((sum, promo) => sum + promo(cart), 0);
}
console.log(checkoutTotal({ total: 9_000, deliveryFee: 700, cheapestItem: 2_190 }, [percentOff(10), freeDelivery])); // 8100import java.util.List;
record Cart(long total, long deliveryFee, long cheapestItem) {} // grosze
// Violation: every new promotion means editing this switch and re-testing all of it.
enum PromoKind { TEN_PERCENT, FREE_DELIVERY, SECOND_HALF_PRICE }
final class PromoCalculator {
static long discount(PromoKind kind, Cart cart) {
return switch (kind) {
case TEN_PERCENT -> cart.total() / 10;
case FREE_DELIVERY -> cart.deliveryFee();
case SECOND_HALF_PRICE -> cart.cheapestItem() / 2;
};
}
}
// Fix: closed for modification, open for extension – a new promotion is a new class.
interface Promotion { long discount(Cart cart); }
record PercentOff(int percent) implements Promotion {
public long discount(Cart cart) { return cart.total() * percent / 100; }
}
record FreeDelivery() implements Promotion {
public long discount(Cart cart) { return cart.deliveryFee(); }
}
record SecondHalfPrice() implements Promotion {
public long discount(Cart cart) { return cart.cheapestItem() / 2; }
}
record Checkout(List<Promotion> promotions) {
long total(Cart cart) {
return cart.total() + cart.deliveryFee() - promotions.stream().mapToLong(p -> p.discount(cart)).sum();
}
}package promotions
type Cart struct {
Total, DeliveryFee, CheapestItem int64 // grosze
}
// Violation: every new promotion means editing this switch and re-testing all of it.
type PromoKind int
const (
TenPercent PromoKind = iota
FreeDeliveryKind
SecondHalfPriceKind
)
func Discount(kind PromoKind, cart Cart) int64 {
switch kind {
case TenPercent:
return cart.Total / 10
case FreeDeliveryKind:
return cart.DeliveryFee
case SecondHalfPriceKind:
return cart.CheapestItem / 2
}
return 0
}
// Fix: closed for modification, open for extension – a new promotion is a new func or type.
type Promotion interface{ Discount(cart Cart) int64 }
// PromotionFunc lets a plain function act as a Promotion, like http.HandlerFunc.
type PromotionFunc func(cart Cart) int64
func (f PromotionFunc) Discount(cart Cart) int64 { return f(cart) }
func PercentOff(percent int64) Promotion {
return PromotionFunc(func(c Cart) int64 { return c.Total * percent / 100 })
}
var (
FreeDelivery = PromotionFunc(func(c Cart) int64 { return c.DeliveryFee })
SecondHalfPrice = PromotionFunc(func(c Cart) int64 { return c.CheapestItem / 2 })
)
func CheckoutTotal(cart Cart, promotions ...Promotion) int64 {
total := cart.Total + cart.DeliveryFee
for _, p := range promotions {
total -= p.Discount(cart)
}
return total
}from collections.abc import Callable, Iterable
from dataclasses import dataclass
from enum import Enum, auto
@dataclass(frozen=True)
class Cart:
total: int # grosze
delivery_fee: int
cheapest_item: int
# Violation: every new promotion means editing this function and re-testing all of it.
class PromoKind(Enum):
TEN_PERCENT = auto()
FREE_DELIVERY = auto()
SECOND_HALF_PRICE = auto()
def discount(kind: PromoKind, cart: Cart) -> int:
match kind:
case PromoKind.TEN_PERCENT:
return cart.total // 10
case PromoKind.FREE_DELIVERY:
return cart.delivery_fee
case PromoKind.SECOND_HALF_PRICE:
return cart.cheapest_item // 2
# Fix: closed for modification, open for extension – a new promotion is a new function.
Promotion = Callable[[Cart], int]
def percent_off(percent: int) -> Promotion:
return lambda cart: cart.total * percent // 100
def free_delivery(cart: Cart) -> int:
return cart.delivery_fee
def second_half_price(cart: Cart) -> int:
return cart.cheapest_item // 2
def checkout_total(cart: Cart, promotions: Iterable[Promotion]) -> int:
return cart.total + cart.delivery_fee - sum(promo(cart) for promo in promotions)
print(checkout_total(Cart(9000, 700, 2190), [percent_off(10), free_delivery])) # 8100The rest of this article is for members
Create a free account or sign in to read it all. Still ahead:
- L – the Liskov Substitution Principle (LSP)
- I – the Interface Segregation Principle (ISP)
- D – the Dependency Inversion Principle (DIP)
- The most common misreadings
- When to use it and when not to
- In practice
- Related topics
- Test yourself