Artykuł · Czysta architektura · Architektura heksagonalna
Czysta architektura: reguła zależności i przypadki użycia w centrum
Clean Architecture Roberta C. Martina bez mitów: cztery kręgi, reguła zależności, porty wejściowe i wyjściowe, prezenter. Struktura i przypadek użycia w C#, TypeScript, Javie, Go i Pythonie oraz uczciwa lista kosztów.
Program lojalnościowy pierogarni Haliny miał być prosty: punkty za zamówienia, nagrody za punkty. Po roku działa w aplikacji mobilnej, w kasie w lokalu i w chatbocie, a reguły wymiany punktów zmieniają się co kwartał. Zespół przebudowuje go według czystej architektury (ang. Clean Architecture) – tak, żeby reguły i przypadki użycia nie wiedziały nic o tym, czy wywołuje je kontroler HTTP, czy bot.
- 2012
- wpis „The Clean Architecture” – Robert C. Martin łączy heksagon, cebulę, BCE i DCI
- 4
- kręgi na klasycznym rysunku – liczba nie jest święta – ważna jest reguła
- 1
- reguła zależności – wszystko inne z niej wynika
Kontekst i siły
- Wiele kanałów – ta sama wymiana punktów z aplikacji, kasy i chatbota.
- Zmienne reguły – biznes chce zmieniać progi i nagrody bez ruszania integracji.
- Długi horyzont – framework webowy i baza zmienią się szybciej niż zasady lojalności.
- Testowalność – przypadki użycia muszą dać się testować w milisekundach.
Robert C. Martin w 2012 roku zauważył, że architektura heksagonalna, cebulowa, Boundary-Control-Entity Ivara Jacobsona i DCI mówią to samo, i zebrał to w jeden rysunek z regułą zależności. W 2017 roku rozwinął temat w książce Clean Architecture.
Struktura
Kręgi narysowane jako zagnieżdżone prostokąty – zewnętrzny zawiera wewnętrzne, a strzałki zależności idą tylko do środka:
| Krąg | Zawiera | Zależy od |
|---|---|---|
| Encje | Reguły biznesu niezależne od aplikacji: LoyaltyAccount.Redeem | niczego |
| Przypadki użycia | Reguły aplikacji: interaktory, porty wejściowe i wyjściowe, DTO żądań i odpowiedzi | encji |
| Adaptery interfejsów | Kontrolery, prezentery, bramy do bazy, mapowanie formatów | przypadków użycia |
| Frameworki i sterowniki | Serwer HTTP, ORM, baza, kolejki, UI | adapterów (tylko „klej”) |
Najmniej znanym, a najciekawszym elementem rysunku Martina jest prawy dolny róg: przepływ sterowania i zależności idą w różnych kierunkach. Kontroler woła interaktor, interaktor woła prezenter – ale interaktor nie zna prezentera, tylko port wyjściowy, który sam zdefiniował:
W wielu projektach port wejściowy jest po prostu publiczną metodą klasy interaktora, a prezenter zastępuje zwracana wartość. To uproszczenie jest w porządku, dopóki przypadek użycia nie zaczyna zwracać typów frameworka (np. IActionResult).
Jak to wygląda w kodzie
Struktura w pięciu stosach
src/
├── Loyalty.Domain/ ← ENTITIES: LoyaltyAccount, Reward, domain errors. No packages.
├── Loyalty.Application/ ← USE CASES: RedeemReward interactor, ports (IAccounts, IRedeemRewardPresenter)
├── Loyalty.Infrastructure/ ← FRAMEWORKS & DRIVERS: EF Core gateways, SMS, clock
└── Loyalty.Web/ ← INTERFACE ADAPTERS + composition root: controllers, presenters, Program.cs
references: Web → Application, Infrastructure → Application → Domainloyalty/
├── loyalty-domain/ ← entities, plain Java, no Spring
├── loyalty-application/ ← use cases + port interfaces (depends on domain)
├── loyalty-adapters/ ← controllers, presenters, JPA gateways (depends on application)
└── loyalty-boot/ ← @SpringBootApplication, wiring (depends on everything)src/
├── domain/ ← entities: loyalty-account.ts (no imports from outside domain/)
├── application/ ← use cases + ports: redeem-reward.ts, ports.ts
├── adapters/ ← http/ (controllers, presenters), persistence/ (Prisma gateways)
└── main.ts ← composition root: builds the object graphloyalty/
├── domain/ ← package domain: entities and rules
├── usecase/ ← package usecase: interactors + port interfaces
├── adapter/
│ ├── http/ ← handlers and presenters
│ └── postgres/ ← gateways implementing usecase ports
└── cmd/loyalty/main.go ← wiringloyalty/
├── domain/ ← dataclasses with behaviour, no framework imports
├── application/ ← use cases + Protocol ports
├── adapters/ ← fastapi_routes.py, presenters.py, sqlalchemy_gateways.py
└── main.py ← composition rootPrzypadek użycia „wymień punkty na nagrodę” z encją, interaktorem, portami i prezenterem:
Interaktor RedeemReward z portami
// ENTITIES (Loyalty.Domain) – rules true for every application of the business
public sealed class LoyaltyAccount(Guid customerId, int points)
{
public Guid CustomerId { get; } = customerId;
public int Points { get; private set; } = points;
public void Redeem(Reward reward)
{
if (Points < reward.Cost) throw new NotEnoughPointsException(Points, reward.Cost);
Points -= reward.Cost;
}
}
// USE CASE (Loyalty.Application) – owns its ports, knows no framework
public sealed record RedeemRewardRequest(Guid CustomerId, string RewardCode);
public sealed record RedeemRewardResponse(string Reward, int PointsLeft);
public interface IAccounts { Task<LoyaltyAccount> Get(Guid id); Task Save(LoyaltyAccount a); }
public interface IRewards { Task<Reward> Get(string code); }
public interface IRedeemRewardPresenter // output port
{
void Success(RedeemRewardResponse response);
void NotEnoughPoints(int has, int needs);
}
public sealed class RedeemReward(IAccounts accounts, IRewards rewards) // the interactor
{
public async Task Execute(RedeemRewardRequest req, IRedeemRewardPresenter presenter)
{
var account = await accounts.Get(req.CustomerId);
var reward = await rewards.Get(req.RewardCode);
try { account.Redeem(reward); }
catch (NotEnoughPointsException e) { presenter.NotEnoughPoints(e.Has, e.Needs); return; }
await accounts.Save(account);
presenter.Success(new RedeemRewardResponse(reward.Name, account.Points));
}
}
// INTERFACE ADAPTER (Loyalty.Web) – a presenter turns the response into HTTP
public sealed class HttpRedeemPresenter : IRedeemRewardPresenter
{
public IResult Result { get; private set; } = Results.StatusCode(500);
public void Success(RedeemRewardResponse r) => Result = Results.Ok(new { r.Reward, r.PointsLeft });
public void NotEnoughPoints(int has, int needs) =>
Result = Results.Problem($"You have {has} points, this reward costs {needs}.", statusCode: 422);
}// ENTITIES – src/domain/loyalty-account.ts
export class NotEnoughPoints extends Error {
constructor(readonly has: number, readonly needs: number) { super("not enough points"); }
}
export class LoyaltyAccount {
constructor(readonly customerId: string, private _points: number) {}
get points() { return this._points; }
redeem(reward: Reward): void {
if (this._points < reward.cost) throw new NotEnoughPoints(this._points, reward.cost);
this._points -= reward.cost;
}
}
// USE CASE – src/application/redeem-reward.ts (imports only from ../domain)
export interface Accounts { get(id: string): Promise<LoyaltyAccount>; save(a: LoyaltyAccount): Promise<void>; }
export interface Rewards { get(code: string): Promise<Reward>; }
export interface RedeemRewardPresenter {
success(r: { reward: string; pointsLeft: number }): void;
notEnoughPoints(has: number, needs: number): void;
}
export class RedeemReward {
constructor(private readonly accounts: Accounts, private readonly rewards: Rewards) {}
async execute(req: { customerId: string; rewardCode: string }, out: RedeemRewardPresenter) {
const account = await this.accounts.get(req.customerId);
const reward = await this.rewards.get(req.rewardCode);
try {
account.redeem(reward);
} catch (e) {
if (e instanceof NotEnoughPoints) return out.notEnoughPoints(e.has, e.needs);
throw e;
}
await this.accounts.save(account);
out.success({ reward: reward.name, pointsLeft: account.points });
}
}
// INTERFACE ADAPTER – src/adapters/http/redeem.route.ts
app.post("/rewards/redeem", async (req, res) => {
await redeemReward.execute(req.body, {
success: (r) => res.json(r),
notEnoughPoints: (has, needs) => res.status(422).json({ error: `You have ${has}, need ${needs}` }),
});
});// ENTITIES – loyalty-domain
public final class LoyaltyAccount {
private final UUID customerId;
private int points;
public LoyaltyAccount(UUID customerId, int points) { this.customerId = customerId; this.points = points; }
public void redeem(Reward reward) {
if (points < reward.cost()) throw new NotEnoughPointsException(points, reward.cost());
points -= reward.cost();
}
public int points() { return points; }
}
// USE CASE – loyalty-application (no Spring, no JPA)
public interface Accounts { LoyaltyAccount get(UUID id); void save(LoyaltyAccount account); }
public interface Rewards { Reward get(String code); }
public interface RedeemRewardPresenter { // output port
void success(String reward, int pointsLeft);
void notEnoughPoints(int has, int needs);
}
public final class RedeemReward { // the interactor
private final Accounts accounts;
private final Rewards rewards;
public RedeemReward(Accounts accounts, Rewards rewards) { this.accounts = accounts; this.rewards = rewards; }
public void execute(UUID customerId, String rewardCode, RedeemRewardPresenter out) {
var account = accounts.get(customerId);
var reward = rewards.get(rewardCode);
try {
account.redeem(reward);
} catch (NotEnoughPointsException e) {
out.notEnoughPoints(e.has(), e.needs());
return;
}
accounts.save(account);
out.success(reward.name(), account.points());
}
}package usecase
import (
"context"
"errors"
"loyalty/domain"
)
// Ports owned by the use case; adapters in adapter/postgres and adapter/http implement them.
type Accounts interface {
Get(ctx context.Context, id string) (*domain.LoyaltyAccount, error)
Save(ctx context.Context, a *domain.LoyaltyAccount) error
}
type Rewards interface {
Get(ctx context.Context, code string) (domain.Reward, error)
}
type RedeemRewardPresenter interface {
Success(reward string, pointsLeft int)
NotEnoughPoints(has, needs int)
}
type RedeemReward struct {
Accounts Accounts
Rewards Rewards
}
func (uc RedeemReward) Execute(ctx context.Context, customerID, code string, out RedeemRewardPresenter) error {
acc, err := uc.Accounts.Get(ctx, customerID)
if err != nil {
return err
}
reward, err := uc.Rewards.Get(ctx, code)
if err != nil {
return err
}
var np *domain.NotEnoughPointsError
if err := acc.Redeem(reward); errors.As(err, &np) {
out.NotEnoughPoints(np.Has, np.Needs)
return nil
} else if err != nil {
return err
}
if err := uc.Accounts.Save(ctx, acc); err != nil {
return err
}
out.Success(reward.Name, acc.Points)
return nil
}from dataclasses import dataclass
from typing import Protocol
from loyalty.domain import LoyaltyAccount, NotEnoughPoints, Reward
class Accounts(Protocol):
def get(self, customer_id: str) -> LoyaltyAccount: ...
def save(self, account: LoyaltyAccount) -> None: ...
class Rewards(Protocol):
def get(self, code: str) -> Reward: ...
class RedeemRewardPresenter(Protocol): # output port
def success(self, reward: str, points_left: int) -> None: ...
def not_enough_points(self, has: int, needs: int) -> None: ...
@dataclass
class RedeemReward: # the interactor: plain Python, no FastAPI, no SQLAlchemy
accounts: Accounts
rewards: Rewards
def execute(self, customer_id: str, reward_code: str, out: RedeemRewardPresenter) -> None:
account = self.accounts.get(customer_id)
reward = self.rewards.get(reward_code)
try:
account.redeem(reward)
except NotEnoughPoints as e:
out.not_enough_points(e.has, e.needs)
return
self.accounts.save(account)
out.success(reward.name, account.points)Dalsza część artykułu dla zalogowanych
Załóż darmowe konto albo zaloguj się, aby przeczytać całość. W dalszej części:
- Czysta, heksagonalna, cebulowa – czym się różnią
- Kompromisy
- Ścieżka migracji
- W praktyce
- Antywzorce
- Powiązane tematy
- Sprawdź się