← All Tips .NET Best Practices — Expectation vs Reality
🔗 Link copied!
01 / 08
a real talk thread · rais helmy

8 slides · software engineering

.NET Best Practices.
The expectation.
The reality.

Everyone talks about Clean Architecture, CQRS, and DDD.
But most teams are still writing God-class controllers
and calling it "enterprise-grade."

#dotnet #cleanarchitecture #cqrs #softwareengineering
→ swipe to continue
02 / 08
topic 1 · project structure

✦ Expectation (best practice)

4 strict layers

✗ Reality (what teams actually do)

One mega project

// ✦ Clean Architecture
Solution/
├── Domain/
│   ├── Entities/
│   └── Events/
├── Application/
│   ├── Commands/
│   ├── Queries/
│   └── Interfaces/
├── Infrastructure/
│   ├── Repositories/
│   └── Persistence/
└── API/
    └── Controllers/

// Each layer has ONE job.
// Dependency only flows inward.
// ✗ What most teams ship
MyProject/
├── Controllers/
│   └── OrderController.cs
│       // 600 lines
│       // calls DbContext directly
│       // sends emails here too
│       // validates input here
│       // maps DTOs here
│       // logs here
│       // handles errors here
├── Models/
└── Data/
    └── AppDbContext.cs
raishelmy.uk/tips/dotnet_best_practices/ rais.helmy · senior .net dev
03 / 08
topic 2 · cqrs + mediatr
✦ Expectation — best practice
Commands for writes. Queries for reads. Each handler does exactly one thing.
MediatR pipeline handles validation, logging, and transactions cross-cuttingly.
Every handler is independently unit-testable with zero setup.
Controller becomes a thin router — no logic.
✗ Reality — what most do
One OrderService with 800 lines doing reads, writes, emails, and PDF generation.
Validation scattered — sometimes in controller, sometimes in service, sometimes nowhere.
"We'll refactor later." (They never do.)
Unit tests need 20 mock setups just to test one method.
// ✦ CQRS done right
public record CreateOrderCommand(string CustomerId, decimal Total) : IRequest<Guid>;

public class CreateOrderHandler : IRequestHandler<CreateOrderCommand, Guid>
{
    public async Task<Guid> Handle(CreateOrderCommand cmd, CancellationToken ct)
    {
        var order = Order.Create(cmd.CustomerId, cmd.Total); // domain logic
        await _repo.AddAsync(order, ct);
        return order.Id; // clean. testable. single responsibility. ✦
    }
}
04 / 08
topic 3 · domain models & validation
✦ Expectation — best practice
Rich domain entities with behaviour. Order.Create() enforces invariants.
FluentValidation in the MediatR pipeline — fails fast before handler runs.
Value Objects for things like Money, Email, PhoneNumber.
✗ Reality — what most do
Anemic models — plain bags of properties with public setters everywhere.
Validation in 4 different places. Or none. Discovered in production.
if (order.Total < 0) written 6 times across the codebase.
// ✦ Rich Domain Entity
public class Order
{
  private Order() {} // no public ctor

  public static Order Create(
    string customerId,
    Money total)
  {
    ArgumentException.ThrowIfNullOrEmpty(
      customerId);
    if (total.Amount <= 0)
      throw new DomainException(
        "Total must be positive");

    return new Order { ... };
  }
}
// ✗ Anemic model (common reality)
public class Order
{
  public int Id { get; set; }
  public string CustomerId { get; set; }
  public decimal Total { get; set; }
  public string Status { get; set; }
  // anyone can set anything
  // no invariants enforced
  // validation lives elsewhere
  // (or nowhere)
}
05 / 08
topic 4 · error handling & logging
✦ Expectation — best practice
Result<T> pattern — errors are values, not exceptions for flow control.
Global exception middleware + RFC 7807 ProblemDetails for all API errors.
Serilog structured logging with Correlation ID on every request.
✗ Reality — what most do
try/catch in every method. Swallowed exceptions. catch (Exception ex) {}
return 200 OK with error message in the body. Always.
Console.WriteLine(ex.Message) as "logging."
// ✦ Result pattern
public async Task<Result<Guid>>
    Handle(CreateOrderCommand cmd)
{
    var customer =
        await _repo.FindAsync(cmd.CustomerId);

    if (customer is null)
        return Result.Fail(
            "Customer not found");

    var order = Order.Create(customer, ...);
    await _repo.AddAsync(order);
    return Result.Ok(order.Id);
}
// ✗ Exception-driven reality
public async Task<IActionResult>
    Create(OrderDto dto)
{
    try {
        var order = new Order();
        order.CustomerId = dto.CustomerId;
        _db.Orders.Add(order);
        await _db.SaveChangesAsync();
        return Ok("success"); // 200 always
    } catch (Exception ex) {
        return Ok(new { error = ex.Message });
        // still 200. still wrong. 💀
    }
}
06 / 08
the real lesson · don't follow blindly

Best practices are a compass,
not a religion.

The engineers who copy Clean Architecture templates into every project without understanding why — are just creating a different kind of mess.

When CQRS makes sense

Complex domain. Different read/write load. Multiple bounded contexts. Enterprise scale. Audit trail needed.

When CQRS is overkill

Simple CRUD API. 3-person startup. MVP with 5 endpoints. When the ceremony costs more than the benefit.

The mark of a senior engineer is not knowing every pattern.
It's knowing which pattern fits which problem — and having the confidence to say "we don't need that here."

07 / 08
practical framework · when to apply what
clean architecture
Use when domain logic is complex
Skip for simple CRUD / internal tools
cqrs + mediatr
Use when reads ≠ writes in complexity
Skip for symmetric 5-endpoint APIs
rich domain models
Use when invariants matter
Skip for pure data passthrough
result<t> pattern
Use when failure is expected behaviour
Skip when exceptions are truly exceptional
microservices
Use when teams & domains are independent
Skip unless you have the ops maturity
the real rule
Fit pattern to problem.
Not problem to pattern.
08 / 08
found this useful?

Rais Helmy Sapiullah

Senior .NET · FlutterFlow · Solution Architect · Cloudflare

I build enterprise .NET systems that are actually maintainable — not just architecturally impressive templates. 6+ years across insurance, defence, utility, and ERP in Malaysia.

WhatsApp — tap to chat
+60 11-1674 5806
Email me
[email protected]
Website & full article
raishelmy.uk
rais.helmy.sapiullah · 2026