# Clean Architecture

Clean Architecture is a software design philosophy that separates the elements of a design into ring levels. The main goal is the separation of concerns, allowing for software that is independent of frameworks, UI, databases, and external agencies.

## 1. The Dependency Rule

The overriding rule that makes this architecture work is the **Dependency Rule**:

> Source code dependencies must point only inward, toward higher-level policies.

Nothing in an inner circle can know anything at all about something in an outer circle. This includes functions, classes, variables, or any other named software entity.

## 2. The Layers (The Onion)

The architecture is often visualized as concentric circles.

### Entities (Innermost Layer)
*   Encapsulate Enterprise-wide business rules.
*   Least likely to change when something external changes (like page navigation or security).
*   Pure logic objects.

### Use Cases
*   Application-specific business rules.
*   Orchestrates the flow of data to and from the entities.
*   Directs entities to use their Enterprise-wide business rules to achieve the goals of the use case.

### Interface Adapters
*   Converts data from the format most convenient for the use cases and entities, to the format most convenient for some external agency (like the Database or the Web).
*   Includes Presenters, Controllers, and Gateways.

### Frameworks and Drivers (Outermost Layer)
*   The glue code.
*   Includes the Database, the Web Framework (e.g., React, Angular, Spring), and devices.
*   Generally, you don't write much code here other than glue code.

## 3. Benefits

1.  **Independent of Frameworks:** The architecture does not depend on the existence of some library of feature laden software. This allows you to use such frameworks as tools.
2.  **Testable:** The business rules can be tested without the UI, Database, Web Server, or any other external element.
3.  **Independent of UI:** The UI can change easily, without changing the rest of the system. A Web UI could be replaced with a console UI, for example, without changing the business rules.
4.  **Independent of Database:** You can swap out Oracle or SQL Server, for Mongo, BigTable, CouchDB, or something else. Your business rules are not bound to the database.

## 4. Implementation Example (Structure)

```text
src/
  domain/           # Entities (No dependencies)
    User.ts
  use-cases/        # Application Logic (Depends on domain)
    CreateUser.ts
  adapters/         # Controllers/Presenters (Depends on use-cases)
    UserController.ts
    UserRepositoryImpl.ts
  infrastructure/   # Frameworks/Drivers (Depends on adapters)
    ExpressServer.ts
    PostgresDB.ts
```

[[programming/solid-principles]]
[[programming/microservices-architecture]]
[[programming/software-testing-basics]]