Clean Architecture

Jul 22, 2024

Clean Architecture Overview

Introduction to Clean Architecture

  • Clean Architecture: Concept popularized by Uncle Bob.
  • Purpose: Organize systems into manageable, maintainable layers.
  • Main Goal: Reduce dependencies of business logic.

Core Principles

  • Business Logic/Core Domain: Central layer. Should be independent of other layers like framework and database.
  • Layered Architecture: Separate tech into layers to manage complex projects better.
  • Independence: Business logic should not depend on external frameworks (e.g., Express, Next.js).

Example Using Express

  • Main App.js: Contains routes which invoke controllers.
  • Get Users Controller: Takes data from request and passes to interactor or use case.
  • Interactor/Use Case: Processes data and performs business logic, returning results without knowing about HTTP framework.
  • Entities: Classes with validation rules reflecting business logic (e.g., User entity with status and receipt).

Avoiding Business Logic Leakage

  • No Front-End/Persistence Dependency: Business logic should not leak into UI or persistence layer.
  • Centralized Validation: Business rules should not be duplicated and leaking.

Persistence Layer & Database Interaction

  • Database Interaction: Should be separated from business rules. Use repositories or data access layers.
  • Abstraction: No direct database logic in business layer; use interfaces and dependency injection.
  • Example: Switch from SQL to another DB without affecting business rules.

Coding Practices

  • Dependency Injection: Pass dependencies dynamically to keep business logic agnostic of specific implementations.
  • Interfaces: Business logic depends on interfaces, not concrete implementations.

Real-World Use Case

  • Email Sending: Change in email sending logic was done in one place due to clean architecture principles.

Data Transfer Objects (DTOs)

  • DTOs: Used to insulate database changes from front-end responses and maintain consistency.
  • Considerations: Can add complexity; consider context and necessity.

Final Thoughts

  • Understanding Clean Architecture: Balancing over-engineering and benefits.
  • Importance: Maintains a clear structure and separations of concerns that scale well with system complexity.