English

Artykuł · SOLID · Strategia

SOLID: pięć zasad projektowania obiektowego bez mitów

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.

Autor · · 32 min czytania

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 case, a test wyświetlacza w kuchni wymaga atrapy z sześcioma metodami. SOLID 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.

5
zasad – SRP, OCP, LSP, ISP, DIP
1987
najstarsza z nich – Barbara Liskov i zasada podstawienia
ok. 2004
akronim SOLID – ułożony przez Michaela Feathersa

Skąd się wzięło SOLID

Zasady powstawały osobno i dopiero później trafiły do jednego worka:

  1. 1987 Barbara Liskov – Wykład „Data Abstraction and Hierarchy” na konferencji OOPSLA – zasada podstawienia.
  2. 1988 Bertrand Meyer – „Object-Oriented Software Construction” – moduły otwarte na rozszerzanie, zamknięte na modyfikacje.
  3. 1996 Robert C. Martin – Seria artykułów w C++ Report: otwarte–zamknięte, podstawienie Liskov, odwrócenie zależności, segregacja interfejsów.
  4. 2000 „Design Principles and Design Patterns” – Martin zbiera zasady projektowania klas w jednym tekście.
  5. ok. 2004 Michael Feathers – Układa z pierwszych liter akronim SOLID.
  6. 2017 „Clean Architecture” – Martin przeformułowuje SRP: moduł odpowiada przed jednym aktorem.
LiteraZasadaJednym zdaniemWzorce, które ją realizują
Spojedyncza odpowiedzialność (Single Responsibility)moduł odpowiada przed jednym aktoremDekorator, Obserwator, Polecenie
Ootwarte–zamknięte (Open/Closed)nowe zachowanie dodajesz nowym kodem, nie edycją staregoStrategia, Dekorator, Metoda szablonowa
Lpodstawienie Liskov (Liskov Substitution)podtyp spełnia kontrakt typu bazowegoKompozyt, Pełnomocnik, Stan
Isegregacja interfejsów (Interface Segregation)klient zależy tylko od metod, których używaAdapter, Fasada
Dodwrócenie zależności (Dependency Inversion)polityka i szczegóły zależą od abstrakcji należącej do politykiAdapter, Fabryka abstrakcyjna, architektura heksagonalna
Diagram: Zasady SOLID i wzorce, które je realizują

S – zasada pojedynczej odpowiedzialności (SRP)

Klasyczne sformułowanie brzmi: klasa powinna mieć tylko jeden powód do zmiany. Martin w Clean Architecture doprecyzował, co znaczy „powód”: moduł powinien odpowiadać przed jednym i tylko jednym aktorem – osobą lub grupą, która poprosi o zmianę.

W pierogarni klasa OrderDocuments 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 Label. 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.

SRP – naruszenie i poprawka

OrderDocuments.cs
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!";
}
order-documents.ts
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!`;
OrderDocuments.java
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!"; }
}
documents.go
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)
}
order_documents.py
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ł

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 joinLines to hydraulika, a nie polityka, więc dzielenie się nią niczego nie sprzęga.

O – zasada otwarte–zamknięte (OCP)

Bertrand Meyer pisał w 1988 roku, że moduły powinny być otwarte na rozszerzanie, ale zamknięte na modyfikacje. 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.

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 switch i ponowne testowanie wszystkich gałęzi.

OCP – naruszenie i poprawka

Promotions.cs
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));
}
promotions.ts
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])); // 8100
Promotions.java
import 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();
    }
}
promotions.go
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
}
promotions.py
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]))  # 8100

Dalsza część artykułu dla zalogowanych

Załóż darmowe konto albo zaloguj się, aby przeczytać całość. W dalszej części:

  • L – zasada podstawienia Liskov (LSP)
  • I – zasada segregacji interfejsów (ISP)
  • D – zasada odwrócenia zależności (DIP)
  • Najczęstsze błędne interpretacje
  • Kiedy stosować, a kiedy nie
  • W praktyce
  • Powiązania
  • Sprawdź się

Załóż darmowe konto · Zaloguj się