Learn C# Β· 15/15

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:

  1. Code to read user input.
  2. Code to validate the input.
  3. Code to open a SQL connection.
  4. Code to save the book to the database.
  5. 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:

  1. Presentation Layer (UI): The face. Consumes user input and displays data. (Console, React, MVC Views).
  2. Business Logic Layer (BLL): The brain. Validations, calculations, rules.
  3. 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:

text
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 logic

Code Example:

csharp
// 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.

csharp
// 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.

csharp
// 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):

bash
# 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.Services

The AAA Pattern

Every unit test follows this structure:

  1. Arrange: Setup variables and objects.
  2. Act: Call the method you want to test.
  3. Assert: Check if the result matches expectations.

Writing a Test

Let's test a simple Calculator.Add method.

File: CalculatorTests.cs

csharp
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.

  1. It's slow.
  2. The database might be down.
  3. 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:

bash
dotnet add MyApp.Tests package Moq

The Code

We want to test that UserService calls Save when the age is valid.

csharp
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

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:

  1. Define a Data Access Layer (DAL) Abstraction:

    • Create an interface named IUserRepository with a single method signature: void AddUser(User user);.
  2. Implement the DAL:

    • Create a class named UserRepository that implements the IUserRepository interface. The AddUser method should simulate saving a user (you can use a Console.WriteLine statement for this).
  3. Refactor the Business Logic Layer (BLL):

    • Create a new UserService class.
    • This class must not have any direct knowledge of the concrete UserRepository. Instead, it should depend on the IUserRepository abstraction.
    • Use Dependency Injection by injecting IUserRepository through 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 RegisterUser method in this new UserService.
    • The RegisterUser method should call the repository's AddUser method only if the user meets the age requirement.
  4. Write a Unit Test:

    • Create a test class named UserServiceTests.
    • Write a test method using xUnit syntax ([Fact]) named RegisterUser_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 AddUser method on the mocked repository was never called.

Expected result

Your final code should consist of four new C# constructs:

  1. IUserRepository interface:

    • Contains one method definition: void AddUser(User user);.
  2. UserRepository class:

    • Implements the IUserRepository interface.
    • Its AddUser method contains the logic for saving a user (e.g., a Console.WriteLine statement).
  3. UserService class:

    • A constructor that accepts IUserRepository as a parameter.
    • A RegisterUser method that takes a user's name and date of birth.
    • This method contains the age-checking business logic.
    • It calls the AddUser method on its repository dependency ONLY if the user is 18 or older.
  4. UserServiceTests class:

    • A test method marked with the [Fact] attribute.
    • The method should instantiate the UserService, injecting a Mock<IUserRepository>.
    • It should call RegisterUser with a date of birth that results in an age less than 18.
    • It must use mock.Verify() to confirm that the AddUser method of the repository was called zero times (Times.Never()).
csharp

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.