Home / Market / Uncle Bob

Uncle Bob

Apply Robert C. Martin (Uncle Bob) principles for clean code, SOLID design, and clean architecture. Use when: (1) reviewing or refactoring code for quality,...

skill★ 00 dlclawhubMIT-0Install in CosmosUpstream Source

Documentation & Preview

Clean Architecture — Detailed Guide

The Core Idea

Separate the software into layers. Each layer has a specific role. Dependencies point inward.

┌──────────────────────────────────────────┐
│         Frameworks & Drivers             │  ← DB, Web, UI, devices
│  ┌────────────────────────────────────┐  │
│  │       Interface Adapters           │  │  ← Controllers, Gateways, Presenters
│  │  ┌──────────────────────────────┐  │  │
│  │  │        Use Cases             │  │  │  ← Application business rules
│  │  │  ┌────────────────────────┐  │  │  │
│  │  │  │      Entities          │  │  │  │  ← Enterprise business rules
│  │  │  └────────────────────────┘  │  │  │
│  │  └──────────────────────────────┘  │  │
│  └────────────────────────────────────┘  │
└──────────────────────────────────────────┘

The Dependency Rule

Source code dependencies must only point inward. Nothing in an inner ring can know anything about an outer ring. This includes functions, classes, variables, types, or any named entity.

Layer Details

Entities (Innermost)

// Pure entity — no imports from outer layers
class Account {
  constructor(
    readonly id: string,
    private balance: number,
  ) {}

  deposit(amount: number) {
    if (amount <= 0) throw new DomainError('Amount must be positive')
    this.balance += amount
  }

  withdraw(amount: number) {
    if (amount > this.balance) throw new InsufficientFundsError()
    this.balance -= amount
  }

  getBalance() { return this.balance }
}

Use Cases

// Use case — depends on entities and port interfaces, nothing else
class TransferFundsUseCase {
  constructor(
    private accountRepo: AccountRepository,  // Port (interface)
    private notifier: TransferNotifier,       // Port (interface)
  ) {}

  async execute(fromId: string, toId: string, amount: number) {
    const from = await this.accountRepo.findById(fromId)
    const to = await this.accountRepo.findById(toId)

    from.withdraw(amount)
    to.deposit(amount)

    await this.accountRepo.save(from)
    await this.accountRepo.save(to)
    await this.notifier.notify(fromId, toId, amount)
  }
}

Interface Adapters

// Controller (adapter) — converts HTTP to use case input
class TransferController {
  constructor(private useCase: TransferFundsUseCase) {}

  async handle(req: HttpRequest): Promise<HttpResponse> {
    const { fromId, toId, amount } = req.body
    await this.useCase.execute(fromId, toId, amount)
    return { status: 200, body: { success: true } }
  }
}

// Repository implementation (adapter) — converts use case port to DB
class PostgresAccountRepository implements AccountRepository {
  async findById(id: string): Promise<Account> {
    const row = await this.db.query('SELECT * FROM accounts WHERE id = $1', [id])
    return new Account(row.id, row.balance)
  }

  async save(account: Account): Promise<void> {
    await this.db.query('UPDATE accounts SET balance = $1 WHERE id = $2',
      [account.getBalance(), account.id])
  }
}

Frameworks & Drivers (Outermost)

Ports and Adapters (Hexagonal Architecture)

Clean Architecture is compatible with hexagonal architecture:

// PORT — defined in use case layer
interface AccountRepository {
  findById(id: string): Promise<Account>
  save(account: Account): Promise<void>
}

// ADAPTER — defined in infrastructure layer
class DrizzleAccountRepository implements AccountRepository {
  // Implementation using Drizzle ORM
}

Crossing Boundaries

When data crosses a boundary, it should be in the form most convenient for the inner circle. Never pass database rows or HTTP request objects into use cases.

Use simple DTOs or value objects:

// Input DTO for use case
interface TransferInput {
  fromAccountId: string
  toAccountId: string
  amount: number
}

// Output DTO from use case
interface TransferResult {
  success: boolean
  newBalance: number
}

The Composition Root

All dependency wiring happens at the outermost layer — the "main" or "composition root":

// main.ts — the only place that knows about ALL concrete implementations
const db = new PostgresDatabase(config.dbUrl)
const accountRepo = new PostgresAccountRepository(db)
const notifier = new EmailTransferNotifier(config.smtp)
const transferUseCase = new TransferFundsUseCase(accountRepo, notifier)
const controller = new TransferController(transferUseCase)

app.post('/transfer', (req, res) => controller.handle(req, res))

Testing Benefits

Each layer can be tested independently:

Common Mistakes

Pragmatic Application