🛠️

Hexagonal Architecture and Clean Architecture Lecture Notes

Jun 28, 2024

Hexagonal Architecture and Clean Architecture Overview

Introduction

  • Hexagonal Architecture a.k.a Ports and Adapters
  • Other similar architectures: Onion Architecture, Clean Architecture
  • Main goal: Decoupling business logic from external dependencies

Benefits

  • Protect business logic from external changes
  • Easier to swap external dependencies (e.g., switching databases)
  • Prevent tightly coupled code, enabling easier future modifications

Clean Architecture Explained

  • Using Clean Architecture at work
  • Clean Architecture can be abstract (e.g., Clean Architecture book by Bob Martin)

Key Components of Clean Architecture

  1. Domain Level Knowledge / Business Logic

    • Diagram with circles representing layers
    • Inner circle (yellow): Business entities and rules
    • Orange ring: Business logic and use cases
    • Blue ring: Frameworks, UIs, Libraries
  2. Business Entities

    • Example: User entity with business rules (e.g., methods ensuring user actions adhere to business rules)
    • Abstracts complexity into entities
  3. Use Cases / Interactors

    • Core of business logic
    • Executes business rules defined in entities
    • Should be free of framework-related code (e.g., Express.js specific code)

Code Walkthrough Example

  • Example with an Express app

  • Initial example:

    • Endpoint directly handling business logic and external calls
  • Problems Identified:

    • Coupling to external libraries (e.g., Express.js)
    • Directly using MySQL in business logic
    • Sending emails within business logic
  • Refactored Example:

    • Created interactors to isolate business logic
    • Removed Express specific code from business logic
    • Created separate functions for database persistence and external interactions (e.g., email sending)

Dependency Management

  • Issue: Business logic still indirectly coupled to specific implementations (e.g., MySQL)
  • Solution: Use Dependency Injection
    • Pass interfaces representing functionalities (e.g., database operations)
    • Implement using function injection, constructor injection, or setter injection
    • Allows swapping implementations easily (e.g., swapping MySQL for MongoDB)

Final Thoughts on Clean Architecture

  • Achieving decoupling through dependency inversion and injection
  • Available frameworks that assist in implementing clean architecture (e.g., Angular)
  • The approach leads to code that's easier to maintain, test, and modify

Conclusion

  • Clean architecture helps in structuring code to be robust against changes and external dependencies
  • Focus on isolating business rules from third-party libraries for cleaner and more scalable code
  • Encourage feedback and engagement (like, subscribe, and comment)