Application Architecture and Best Practices
8 min read
Welcome back, coder! π
By now, you likely know how to write a foreach loop, define a class, and maybe even throw a try-catch block around code that scares you. But here is the hard truth: Writing code that computers understand is easy. Writing code that humans understand (and can maintain) is hard.
Today, we are graduating from "It works on my machine" to "This is enterprise-grade engineering." ποΈ
We are going to cover how to structure your application so it doesn't collapse under its own weight, how to follow the SOLID principles (the holy grail of OOP), and how to write tests so you can deploy on Fridays without fear.
1. Separation of Concerns and N-Tier Architecture π°
The Definition
Separation of Concerns (SoC) is a design principle for separating a computer program into distinct sections such that each section addresses a separate concern. A "concern" is a set of information that affects the code of a computer program.
The Problem: The "God Class"
Imagine you are building a Console App to manage a library. You open Program.cs and you write:
- Code to read user input.
- Code to validate the input.
- Code to open a SQL connection.
- Code to save the book to the database.
- Code to print "Success" to the screen.
This is called Spaghetti Code. π If you want to change the database from SQL Server to PostgreSQL, you have to touch the same file that handles printing text to the screen. You risk breaking the UI just to fix the database.
The Solution: N-Tier Architecture
We split the application into layers (tiers). In C# development, the most common standard is the 3-Tier Architecture:
- Presentation Layer (UI): The face. Consumes user input and displays data. (Console, React, MVC Views).
- Business Logic Layer (BLL): The brain. Validations, calculations, rules.
- Data Access Layer (DAL): The hands. Talks to the database, file system, or external APIs.
Analogy: Think of a restaurant.
- Presentation: The Waiter (takes order, brings food).
- Business Logic: The Chef (cooks, ensures ingredients are valid, follows recipes).
- Data Access: The Supplier (retrieves raw ingredients from the warehouse).
The Waiter doesn't cook. The Chef doesn't talk to the customer. The Supplier doesn't set the table.
Practical Implementation
In a C# Solution, this usually looks like three separate Class Library projects referenced by a main executable.
Folder/Project Structure:
MyApp.Solution
β
βββ MyApp.Web (Presentation)
β βββ Controllers/
β βββ UsersController.cs <-- Calls Service
β
βββ MyApp.Services (Business Logic)
β βββ UserService.cs <-- Validates user, Calls Repository
β
βββ MyApp.Data (Data Access)
βββ UserRepository.cs <-- SQL/Entity Framework logicCode Example:
// 1. Data Access Layer (DAL)
// Only cares about the Database.
public class UserRepository
{
public void Save(User user)
{
// Imagine Entity Framework Core code here
_dbContext.Users.Add(user);
_dbContext.SaveChanges();
}
}
// 2. Business Logic Layer (BLL)
// Cares about rules.
public class UserService
{
private readonly UserRepository _repo = new UserRepository();
public void RegisterUser(string name, int age)
{
if (age < 18)
{
throw new Exception("User is too young.");
}
// Maps input to domain object
var user = new User { Name = name, Age = age };
// Passes to DAL
_repo.Save(user);
}
}
// 3. Presentation Layer
// Cares about the user interaction.
public class Program
{
public static void Main()
{
var service = new UserService();
try
{
service.RegisterUser("Alice", 20);
Console.WriteLine("Success!");
}
catch(Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}2. SOLID Principles: Writing Maintainable Code π
SOLID is an acronym introduced by Robert C. Martin (Uncle Bob). These are the five commandments of Object-Oriented Programming.
S - Single Responsibility Principle (SRP)
Definition: A class should have one, and only one, reason to change.
Problem: You have a Report class that calculates data and saves it to a PDF. If the calculation logic changes, you edit the file. If the PDF library updates, you edit the same file.
Solution: Split it. ReportCalculator calculates. PdfExporter saves.
O - Open/Closed Principle (OCP)
Definition: Software entities should be open for extension, but closed for modification.
Problem: You have a function that calculates area. It has a giant if/else block checking if the shape is a Rectangle or Circle. If you add a Triangle, you have to modify the tested, working code of the calculator.
Solution: Use Polymorphism.
// BAD
public double GetArea(object shape) {
if (shape is Circle c) return c.Radius * c.Radius * Math.PI;
// adding Triangle requires changing this method
}
// GOOD
public abstract class Shape { public abstract double Area(); }
public class Circle : Shape { ... }
public class Triangle : Shape { ... }
// The calculator doesn't need to change even if you add 100 new shapes.
public double GetArea(Shape shape) => shape.Area(); L - Liskov Substitution Principle (LSP)
Definition: Subtypes must be substitutable for their base types without altering the correctness of the program.
Problem: The famous "Ostrich" problem. You have a Bird class with a Fly() method. You create an Ostrich class that inherits from Bird. When Ostrich.Fly() is called, it throws an exception because ostriches can't fly. This breaks LSP because you can't trust a Bird object to actually fly.
Solution: Create more specific interfaces or base classes (e.g., IFlyingBird, INonFlyingBird).
I - Interface Segregation Principle (ISP)
Definition: Clients should not be forced to depend upon interfaces that they do not use.
Problem: You have an interface IMachine with methods Print(), Scan(), and Fax(). You implement a simple Inkjet printer. You are forced to implement Scan() and Fax() just to throw "NotImplementedException".
Solution: Split the interfaces. IPrinter, IScanner, IFax. Your Inkjet only implements IPrinter.
D - Dependency Inversion Principle (DIP)
Definition: High-level modules should not depend on low-level modules. Both should depend on abstractions.
Problem: Your UserService creates a new SqlUserRepository() inside its constructor. Your business logic is now permanently glued to SQL Server. You cannot switch to a cloud database or run tests without a real database.
Solution: Dependency Injection (DI). Ask for an interface in the constructor.
// Dependency Injection in action
public class UserService
{
private readonly IUserRepository _repo;
// We ask for the Interface (Abstraction)
// We don't care if it's SQL, Oracle, or a Mock file.
public UserService(IUserRepository repo)
{
_repo = repo;
}
}3. Unit Testing Basics with xUnit π§ͺ
Fun Fact: Developers spend 70% of their time reading code and debugging, and only 30% writing new code. Unit tests flip this script.
The Definition
Unit Testing is the practice of testing small, isolated pieces of code (usually individual methods) to ensure they function correctly.
The Setup (Industry Standard)
While NUnit and MSTest exist, xUnit is currently the most popular framework for .NET Core / .NET 5+ development because it is lightweight and enforces better patterns.
Getting Started (Terminal):
# Create a solution
dotnet new sln -n MyApp
# Create a Class Library (Logic)
dotnet new classlib -n MyApp.Services
# Create a Test Project (xUnit)
dotnet new xunit -n MyApp.Tests
# Add reference (So the test project can see the code)
dotnet add MyApp.Tests reference MyApp.ServicesThe AAA Pattern
Every unit test follows this structure:
- Arrange: Setup variables and objects.
- Act: Call the method you want to test.
- Assert: Check if the result matches expectations.
Writing a Test
Let's test a simple Calculator.Add method.
File: CalculatorTests.cs
using Xunit; // The testing framework
using MyApp.Services; // Your code
public class CalculatorTests
{
[Fact] // This attribute tells xUnit "This is a test"
public void Add_ShouldReturnSum_WhenNumbersArePositive()
{
// 1. Arrange
var calculator = new Calculator();
int a = 5;
int b = 10;
// 2. Act
int result = calculator.Add(a, b);
// 3. Assert
Assert.Equal(15, result);
}
}To run tests, simply type dotnet test in your terminal. If you see green, you are a genius. If you see red, you are a developer. π΄π’
4. Mocking Dependencies for Isolated Testing π
The Problem
Remember the UserService from earlier? It depended on IUserRepository.
If we want to test the logic "User is too young", we do not want to actually connect to a real database.
- It's slow.
- The database might be down.
- We don't want to insert "Test User" into our production table.
The Solution: Mocking
Mocking creates a "fake" version of an interface that behaves exactly how we tell it to for the duration of the test.
We use a library called Moq (pronounced "Mock" or "Mock-you").
Installation:
dotnet add MyApp.Tests package MoqThe Code
We want to test that UserService calls Save when the age is valid.
using Xunit;
using Moq;
using MyApp.Services;
using MyApp.Data;
public class UserServiceTests
{
[Fact]
public void RegisterUser_ShouldCallSave_WhenUserIsValid()
{
// 1. Arrange
// Create a fake version of the Interface
var mockRepo = new Mock<IUserRepository>();
// Inject the FAKE object into the service
var service = new UserService(mockRepo.Object);
// 2. Act
service.RegisterUser("John Doe", 25);
// 3. Assert
// Verify that the Save method was called exactly once with any User object
mockRepo.Verify(repo => repo.Save(It.IsAny<User>()), Times.Once);
}
}Why this is cool: We just tested the business logic without needing a SQL server installed, without network cables, and in 0.01 seconds.
π Further Reading & Resources
- Official .NET Architecture Guides
- xUnit Documentation
- Moq Quickstart
- Dependency Injection in ASP.NET Core
Now, go refactor that spaghetti code! πβ‘οΈποΈ
Challenge
You have been tasked with refactoring a monolithic GodUserService class that violates several core software design principles. It currently handles user input validation, business logic, and direct data access all within a single method, making it difficult to maintain, extend, and test.
Your goal is to refactor this code to follow Separation of Concerns (SoC), the Single Responsibility Principle (SRP), and the Dependency Inversion Principle (DIP). After refactoring, you will write a unit test for the new business logic layer to ensure its correctness in isolation.
Your Tasks:
Define a Data Access Layer (DAL) Abstraction:
- Create an interface named
IUserRepositorywith a single method signature:void AddUser(User user);.
- Create an interface named
Implement the DAL:
- Create a class named
UserRepositorythat implements theIUserRepositoryinterface. TheAddUsermethod should simulate saving a user (you can use aConsole.WriteLinestatement for this).
- Create a class named
Refactor the Business Logic Layer (BLL):
- Create a new
UserServiceclass. - This class must not have any direct knowledge of the concrete
UserRepository. Instead, it should depend on theIUserRepositoryabstraction. - Use Dependency Injection by injecting
IUserRepositorythrough the constructor. - Move the business logic (validating the user's name and checking if they are 18 or older) from the old class into a
RegisterUsermethod in this newUserService. - The
RegisterUsermethod should call the repository'sAddUsermethod only if the user meets the age requirement.
- Create a new
Write a Unit Test:
- Create a test class named
UserServiceTests. - Write a test method using xUnit syntax (
[Fact]) namedRegisterUser_ShouldNotAddUser_WhenUserIsUnderage. - Inside this test, use the Moq library to create a mock of the
IUserRepository. - Follow the Arrange-Act-Assert pattern to test the scenario where a user under 18 is registered.
- The assertion should verify that the
AddUsermethod on the mocked repository was never called.
- Create a test class named
Expected result
Your final code should consist of four new C# constructs:
IUserRepositoryinterface:- Contains one method definition:
void AddUser(User user);.
- Contains one method definition:
UserRepositoryclass:- Implements the
IUserRepositoryinterface. - Its
AddUsermethod contains the logic for saving a user (e.g., aConsole.WriteLinestatement).
- Implements the
UserServiceclass:- A constructor that accepts
IUserRepositoryas a parameter. - A
RegisterUsermethod that takes a user's name and date of birth. - This method contains the age-checking business logic.
- It calls the
AddUsermethod on its repository dependency ONLY if the user is 18 or older.
- A constructor that accepts
UserServiceTestsclass:- A test method marked with the
[Fact]attribute. - The method should instantiate the
UserService, injecting aMock<IUserRepository>. - It should call
RegisterUserwith a date of birth that results in an age less than 18. - It must use
mock.Verify()to confirm that theAddUsermethod of the repository was called zero times (Times.Never()).
- A test method marked with the