Tale of Software Architect(ure): Part 13 (Clean Architecture)
Saiful Islam Rasel
Senior Engineer, SDE @ bKash | Ex: AsthaIT | Sports Programmer | Problem Solver | FinTech | Microservice | Java | Spring-boot | C# | .NET | PostgreSQL | DynamoDB | JavaScript | TypeScript | React.js | Next.js | Angular
Story:
In this world, Allah is the most powerful and only independent who doesn't need any help or something like that. Allah creates the whole world and all the creatures. Human is one of the best creature of Allah. He also creates a dependency chain that should be followed for maintaining the balance. If anyone want to break the chain or so called break the rules then a very unexpected and dangerous things happen. Which cost a very big damage in the system.
In the right hand part of the below picture, I try to draw a dependency flow of the universe where Allah (SWT) is one and only independent and all other parts are dependent of him directly or indirectly.
Previously I had written details about the Clean Architecture in Random Topic - 32 . You can check it out and then continue from the below section.
Clean Architecture:
Clean Architecture is a software design philosophy introduced by Robert C. Martin (Uncle Bob) in his book Clean Architecture: A Craftsman’s Guide to Software Structure and Design. The main idea is to create a system that is flexible, maintainable, and independent of frameworks, databases, UI, or any external services. This is achieved by organizing code into layers, ensuring that each layer has a clear responsibility and that core business logic remains isolated from implementation details.
Key Concepts of Clean Architecture
Context
In software development, it is common to build systems that are initially easy to manage but become hard to maintain as they grow. Typically, these systems have tightly coupled components like user interfaces, databases, and business logic, making it difficult to make changes without breaking things or introducing bugs.
Developers often struggle to keep their codebases flexible, testable, and maintainable over time. Frameworks evolve, databases change, and new user interfaces are required. These changes often result in complex refactoring efforts that lead to brittle code and high development costs.
Problem
The main problem is tight coupling between the different layers of an application, especially between the business logic, frameworks, and external services. This creates several issues:
Solution
Clean Architecture provides a structured approach to solving these problems by separating the application into layers, with clear boundaries and dependency rules:
Separation of Concerns: The architecture defines distinct layers (entities, use cases, interface adapters, frameworks/drivers), each responsible for a specific type of functionality. This makes the system more understandable and easier to maintain.
Dependency Rule: Clean Architecture dictates that dependencies flow inwards (towards core business logic). The innermost layers (entities, use cases) should know nothing about outer layers (frameworks, UI, or databases). Outer layers depend on the inner layers by adhering to the inversion of control principle (e.g., using interfaces to decouple dependencies).
Testability and Flexibility: By isolating business logic from external dependencies, Clean Architecture enables easier testing. Each layer can be tested in isolation without requiring real databases or external services. This increases confidence in refactoring and adding new features.
Maintainability: The architecture encourages writing clear, modular code that separates business logic from implementation details. This improves long-term maintainability, as developers can change external components (e.g., switching from SQL to NoSQL) without modifying the core system.
Practical Example: E-Commerce Order System
Let’s apply Clean Architecture principles to an order processing system for an e-commerce platform.
领英推荐
Entities (Core Business Logic):
class Order:
def __init__(self):
self.items = []
def add_item(self, product, quantity):
# Business logic for adding an item
self.items.append((product, quantity))
def calculate_total(self):
return sum([product.price * quantity for product, quantity in self.items])
Use Cases (Application Logic):
class PlaceOrder:
def __init__(self, order_repo, payment_service):
self.order_repo = order_repo
self.payment_service = payment_service
def execute(self, order, customer):
# Ensure the order is valid
if order.calculate_total() > customer.balance:
raise Exception("Insufficient balance")
# Handle payment processing
self.payment_service.process_payment(customer, order.calculate_total())
# Store the order
self.order_repo.save(order)
Interface Adapters (Data Transformation):
class OrderRepository:
def __init__(self, db):
self.db = db
def save(self, order):
# Convert order to database format and save
self.db.insert("orders", {"items": order.items, "total": order.calculate_total()})
Frameworks and Drivers (External Services):
class PaymentService:
def process_payment(self, customer, amount):
# External service handling the payment
external_payment_gateway.charge(customer.account, amount)
Summary:
Clean Architecture is a software design philosophy created by Robert C. Martin (Uncle Bob) that aims to produce systems that are flexible, maintainable, and independent of frameworks, databases, or external services. The main goal is to separate concerns by organizing code into layers, ensuring that core business logic (entities) is isolated from implementation details like UI, databases, and frameworks. It promotes creating adaptable and resilient systems by isolating business logic from external dependencies and organizing the codebase into well-defined, decoupled layers.
Previous Parts: