C# / .NET Compendium PLEN
.NET / C# / SOLID, Clean Code, DI

Clean Code

Clean Code is a set of principles and practices for writing code that is readable, understandable and easy to maintain - not only for the computer, but above all for the people who will read and modify it (including you in six months). The term was popularised by Robert C. Martin in the book "Clean Code" (2008).

The key idea: code is read far more often than it is written, so optimising for readability pays off.

Main principles

1. Naming matters

Names of variables, functions and classes should clearly say what they do - with no need for a comment.

// Bad
var d = 30; // days until expiry
decimal Calc(decimal a, decimal b) => a * b * 0.23m;

// Dobrze
var daysUntilExpiration = 30;
decimal CalculateVatAmount(decimal netPrice, decimal quantity)
{
    return netPrice * quantity * VAT_RATE;
}

2. Functions do one thing and are short

If a function has "and" in its name ("FetchAndSave") or you have to scroll to read it - that's a sign it does too much.

// Bad - the function does 3 different things
public async Task ProcessOrder(Order order)
{
    // walidacja
    if (order.Items.Count == 0) throw new Exception("empty");
    // zapis do bazy
    await db.Orders.InsertAsync(order);
    // sending the email
    await mailer.Send(order.CustomerEmail, "Potwierdzenie");
}

// Dobrze - rozbite na czytelne kroki
public async Task ProcessOrder(Order order)
{
    ValidateOrder(order);
    await SaveOrder(order);
    await SendConfirmationEmail(order);
}

3. Avoid duplication (DRY - Don't Repeat Yourself)

Repeated code is a place where a bug will have to be fixed in many places at once.

4. Comments explain "why", not "what"

Good code says what it does by itself. A comment makes sense where you need to explain a decision that isn't obvious from the code alone.

// Bad - the comment describes obvious code
// increment the counter by 1
counter++;

// Good - the comment explains a non-obvious reason
// Retry with a delay, because the hub.ag3nts.org API sometimes returns 429
// with parallel requests from many agents
await Task.Delay(1000);

5. Small classes/modules with a clear responsibility

This is basically SOLID in a nutshell - every module should have one clear reason to exist (see the Single Responsibility Principle we discussed with SOLID).

6. Error handling is part of the logic, not an add-on

// Bad - the error disappears silently
try
{
    await agent.Run();
}
catch (Exception e)
{
    Console.WriteLine("error");
}

// Good - the error is visible and informative
try
{
    await agent.Run();
}
catch (Exception error)
{
    logger.Error($"Agent {agent.Name} failed: {error.Message}", error);
    throw new AgentExecutionException(agent.Name, error);
}

7. Consistency and formatting

One style across the whole project (hence the popularity of ESLint/Prettier in JS, StyleCop/EditorConfig in C#) - less visual "noise", and the brain doesn't have to switch between conventions.

The "clean code" test

A few helper questions worth asking yourself when looking at code: - Will someone else (or me in 3 months) understand this without an explanation? - Does the function name say exactly what it does - nothing more, nothing less? - Could I test this without wrapping half the application in mocks? - Does a change in one place not force changes in five others?


Clean Code and SOLID overlap heavily - SOLID is more about structural rules (how to divide responsibilities between classes/modules), while Clean Code is a broader set of practices at the level of style and readability of individual functions, names and comments.

Buy me a coffee