Article · Clean Architecture · Hexagonal Architecture
Clean Architecture: the dependency rule and use cases at the centre
Robert C. Martin's Clean Architecture without the myths: four circles, the dependency rule, input and output ports, the presenter. Structure and a use case in C#, TypeScript, Java, Go and Python, plus an honest list of costs.
The loyalty programme at Halina's pierogi place was supposed to be simple: points for orders, rewards for points. A year later it runs in the mobile app, at the till in the restaurant and in a chatbot, and the points-exchange rules change every quarter. The team rebuilds it following Clean Architecture – so that the rules and use cases know nothing about whether they are called by an HTTP controller or a bot.
- 2012
- "The Clean Architecture" post – Robert C. Martin unifies hexagon, onion, BCE and DCI
- 4
- circles in the classic drawing – the number isn't sacred – the rule is
- 1
- dependency rule – everything else follows from it
Context and forces
- Many channels – the same points exchange from the app, the till and the chatbot.
- Changing rules – the business wants to change thresholds and rewards without touching integrations.
- A long horizon – the web framework and the database will change faster than the loyalty rules.
- Testability – use cases must be testable in milliseconds.
In 2012, Robert C. Martin noticed that hexagonal architecture, onion architecture, Ivar Jacobson's Boundary-Control-Entity and DCI all say the same thing, and gathered them into one drawing with the dependency rule. In 2017 he expanded the topic in the book Clean Architecture.
Structure
The circles drawn as nested rectangles – the outer one contains the inner ones, and dependency arrows point only inwards:
| Circle | Contains | Depends on |
|---|---|---|
| Entities | Business rules independent of any application: LoyaltyAccount.Redeem | nothing |
| Use cases | Application rules: interactors, input and output ports, request and response DTOs | entities |
| Interface adapters | Controllers, presenters, database gateways, format mapping | use cases |
| Frameworks and drivers | HTTP server, ORM, database, queues, UI | adapters (just "glue") |
The least known and most interesting part of Martin's drawing is the lower-right corner: the flow of control and the dependencies go in different directions. The controller calls the interactor, the interactor calls the presenter – but the interactor doesn't know the presenter, only an output port it defined itself:
In many projects the input port is simply a public method of the interactor class, and the presenter is replaced by a return value. That simplification is fine as long as the use case doesn't start returning framework types (e.g. IActionResult).
What it looks like in code
Structure in five stacks
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 rootThe "redeem points for a reward" use case with an entity, an interactor, ports and a presenter:
The RedeemReward interactor with ports
// 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)The rest of this article is for members
Create a free account or sign in to read it all. Still ahead:
- Clean, hexagonal, onion – how they differ
- Trade-offs
- Migration path
- In practice
- Anti-patterns
- Related topics
- Test yourself