Clean Architecture ๐Ÿงน

Clean Architecture, proposed by Robert C. Martin, is built around one central idea: dependencies point inward. Your business logic should never depend on your database, your framework, or your delivery mechanism. They depend on it.

Clean Architecture

The layers

Each layer depends only on the layer inside it โ€” never outward:

  1. Entities โ€” Core business objects and rules. No dependencies on anything else.
  2. Use Cases โ€” Application-specific business logic. Orchestrates entities to fulfill a specific scenario.
  3. Interface Adapters โ€” Translates data between the format your use cases need and the format external systems provide (controllers, presenters, gateways).
  4. Frameworks and Drivers โ€” The outermost layer: databases, web frameworks, UI. These are details, not decisions.

The dependency rule

Strictly unidirectional. Inner layers define interfaces; outer layers implement them. This is what makes the architecture testable โ€” you can swap your database or your web framework without touching your business logic.

When it works well

Clean Architecture shines in applications with complex business rules that need to survive framework changes, team rotations, or long maintenance cycles. If your domain logic is the most valuable part of your system (and it usually is), protecting it from infrastructure noise is worth the extra structure.

When it's too much

For a simple CRUD API or a short-lived prototype, four layers of indirection is overhead that slows you down without paying off. The value of Clean Architecture is proportional to the complexity of your domain โ€” if your domain fits in one file, the architecture probably shouldn't span four packages.

Project structure

  • ๐Ÿ“ interfaces
    • ๐Ÿ“„ OrderController.java (Entrypoint)
  • ๐Ÿ“ application
    • ๐Ÿ“„ OrderUseCase.java
  • ๐Ÿ“ domain
    • ๐Ÿ“ entities
      • ๐Ÿ“„ Order.java
    • ๐Ÿ“ services
      • ๐Ÿ“„ OrderService.java
  • ๐Ÿ“ infrastructure
    • ๐Ÿ“ repositories
      • ๐Ÿ“„ OrderRepository.java (Interface)
    • ๐Ÿ“ drivers
      • ๐Ÿ“ db
        • ๐Ÿ“„ OrderRepositoryImpl.java
        • ๐Ÿ“„ UserRepositoryImpl.java

The structure is similar to Hexagonal Architecture, but Clean Architecture emphasizes the layering and dependency direction while Hexagonal emphasizes ports and adapters as the mechanism for isolation. In practice, they lead to similar project structures and can be used interchangeably depending on which mental model resonates more with your team.

Sources