Principled N-Tier Design or, a Solution to the Solution Problem Steve | ardalis.com Telerik, Inc.
The Problem
Solution Level Pain Too Many Projects Too Few Projects Incorrect Abstraction The “Goldilocks” Solution – “Just right”
Relevant Principles Common Closure Principle Common Reuse Principle Stable Dependencies Principle Stable Abstractions Principle Separation of Concerns Dependency Inversion Principle
Common Closure Principle Classes that change together are packaged together.
Common Reuse Principle Classes that are used together are packaged together.
Stable Dependencies Principle Depend in the direction of stability.
Stable Abstractions Principle Abstractness increases with stability. Stability Abstractness Ideal Rigid Useless
More Principles Separation of Concerns Establish boundaries to separate behaviors and responsibilities within a system. Dependency Inversion Depend on abstractions, not concrete implementations.
DEMO A Simple Guestbook Application
Testability Testability correlates with: – Loose coupling – Separation of Concerns – Maintainability You don’t have to have unit tests to have testable code! – Unit tests prove (or disprove) testability
DEMO Adding “Unit” Tests
SMTP4DEV
Incremental Improvement From a Single Project – Separate responsibilities using folders – Add Project(s) From Many Projects – Create a new Solution with only what you need – Spin off separate applications into own solutions
DEMO Separation via Folders (still 1 project)
Problems Tests are still not unit tests – Tight coupling – Static Cling – Dependence on Data and Infrastructure concerns Nothing to prevent improper referencing of classes – e.g. UI code can call DAL code directly and bypass business logic UI Content Folders mixed with Application Code Folders
Onion Architecture aka Ports and Adapters, aka Hexagonal Architecture Core models and interfaces at center Infrastructure and Implementation depends on Core UI depends on Core and has access to Infrastructure
Onion Architecture
DEMO Introduce Abstractions and Invert Dependencies (in folders)
Results Yay! Unit Tests that work! Boo! Still nothing to prevent improper referencing of classes – e.g. UI code can call DAL code directly and bypass business logic Boo! Still mixing content and code folders
DEMO Refactor into Projects
Results Testable Code Separation of Concerns Loose Coupling Minimal logic in UI layer A solid foundation for a maintainable application!
Automate One Click Build One Click Test
DEMO Solution Automation – Build Scripts
DEMO More Tests
References Separation of Concerns - Hexagonal Architecture - Onion Architecture - More Onion Architecture - New is Glue - Pluralsight Resources N-Tier Application Design in C# Design Patterns Library SOLID Principles of OO Design
Thanks! Find me at We’re hiring developers and trainers at Telerik!