System Design Cases
Clean Architecture
Clean Architecture (Robert C. Martin, 2012). Concentric circles — Entities, Use Cases, Interface Adapters, Frameworks & Drivers — held together by the Dependency Rule (outer points inward). Four scenarios: happy-path request from controller through presenter to use case to entity to driven port to adapter; unit-testing the use case in isolation with in-memory repos; swapping a framework (Postgres -> Mongo) without touching the inner rings; and an antipattern showing what happens when the dependency rule is violated.
Clean architecture: dependency rule and boundary contracts
Clean Architecture делает policy независимой от mechanisms через Dependency Rule: source-code dependencies point inward. Контроллер и presenter — adapters; web framework и database — outer details. Это правило dependency direction, а не требование ровно четырёх кругов и не обещание, что любой datastore можно заменить без изменения query, consistency и migration design.
Что утверждает паттерн — и чего он не гарантирует
- Martin’s Dependency Rule says source-code dependencies point inward; runtime flow can cross outward through inner-owned interfaces.
- The four circles are schematic, not a mandatory package count.
- Simple boundary data prevents outer framework/database formats from becoming inner policy dependencies.
- Framework/database independence reduces source coupling; real replacement still requires capability, data, performance and failure-semantic work.
Границы и компоненты
| Компонент | Ответственность |
|---|---|
| Web Framework and Route | Обрабатывает transport/auth concerns и вызывает controller. |
| Input Controller Adapter | Преобразует request DTO в use-case input boundary. |
| Application Use Case | Содержит application-specific policy и orchestration. |
| Enterprise or Domain Entities | Содержат наиболее общие business rules. |
| Use-Case Output Boundary | Inner-owned result interface, implemented by presenter. |
| Presenter Adapter | Формирует view model без передачи entities наружу как UI contract. |
| Repository Boundary | Inner-owned persistence capabilities and outcomes. |
| Database Adapter | Переводит repository operations в конкретные transactions/queries. |
Сценарии
Execute a use case across boundaries
The route gives a transport DTO to the controller; controller creates simple input data; use case applies entity policy and returns through an inner-owned output boundary.
Проверяемый исход: No framework request, ORM row or presenter type is named by inner policy.
Map boundary data explicitly
Database/framework representations are translated at adapters. The use case receives only data convenient for its policy and the presenter receives an explicit result model.
Проверяемый исход: Changing a framework mapping does not silently change entity or use-case contracts.
Migrate a database detail safely
A candidate adapter must satisfy repository capability/transaction/query tests and migrate data. The dependency rule isolates source coupling but does not manufacture missing datastore semantics.
Проверяемый исход: Storage cutover occurs only after shadow comparisons and rollback gates pass.
Test policy without frameworks
A test invokes the input boundary and substitutes repository/output interfaces; no web server or production database is required. This improves testability but does not replace integration tests.
Проверяемый исход: Unit policy evidence and adapter integration evidence remain separate and both are required.
Failure, concurrency и evolution checklist
- Test dependency rules statically and test adapters against semantic contracts.
- Model transaction conflict, unavailable dependency and cancellation as explicit boundary outcomes.
- Keep authn/authz placement and trusted identity data explicit; layering does not provide security.
- Run restore/migration and integration tests in addition to policy unit tests.
Метрики, units и допущения
- Dependency-rule conformance can be counted as forbidden inward imports = 0; this is not a runtime reliability metric.
- Storage migration compares rows/keys, invariant violations, hash mismatch rate and replication lag with units.
- Latency budget includes controller mapping, use case, repository and presentation; a clean dependency graph does not reduce milliseconds automatically.
Числа здесь — размерностные формулы или явно помеченные учебные inputs. Паттерн архитектуры сам по себе не задаёт SLA, throughput, latency или fault tolerance.
Связанные темы
[CONCEPT]hexagonal-ports-adapters
Первичные источники
Scope note
The dependency rule is a design constraint. It does not guarantee good domain modelling, low latency, safe data migration, availability, authorization or correct transaction semantics.