Clean Architecture

Robert C. Martin's concentric layers with the dependency rule pointing inward; how it relates to hexagonal and onion architectures and how to apply it pragmatically.

Intent

Clean architecture arranges code in concentric circles: Entities (enterprise business rules) → Use cases (application business rules) → Interface adapters (controllers, presenters, gateways) → Frameworks and drivers (web, DB, UI). The dependency rule: source code dependencies point only inward. Inner layers know nothing about outer layers.

flowchart TB
  subgraph FW[Frameworks & drivers: Spring, DB, Kafka, UI]
    subgraph IA[Interface adapters: controllers, repositories impl, mappers]
      subgraph UC[Use cases: PlaceOrder, CancelOrder]
        EN[Entities: Order, Money, Customer]
      end
    end
  end

Relationship to other styles

Hexagonal (ports and adapters), onion architecture and clean architecture share the same core idea: business logic in the middle, infrastructure at the edges, dependencies inward. Clean architecture adds explicit use case classes and presenter concepts.

Pragmatic Java project structure

order-service/
  domain/        Order, OrderLine, Money, domain events (no framework imports)
  application/   PlaceOrderUseCase, ports (OrderRepository, PaymentGateway)
  adapters/
    in/web/      OrderController, request/response DTOs
    in/messaging/ OrderCommandListener
    out/persistence/ JpaOrderRepository, entities
    out/payment/ PspPaymentGateway
  bootstrap/     Spring configuration wiring adapters to ports

Enforce with ArchUnit:

@ArchTest
static final ArchRule domainIsPure = noClasses().that().resideInAPackage("..domain..")
    .should().dependOnClassesThat().resideInAnyPackage("org.springframework..", "jakarta.persistence..");

Pros and cons

Pros Cons
Framework independence, testability Boilerplate (DTOs, mappers)
Business rules easy to find Can slow small teams on simple domains
Long-lived systems age better Misapplied as rigid ceremony

Interview questions

Should JPA annotations be allowed on domain entities?

Purists say no (separate persistence models). Pragmatically, many teams accept JPA annotations on domain entities for simplicity if the domain logic stays independent of persistence behaviour. Decide per system complexity and document it.