📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Code review: a team calls this solution "Clean Architecture". The domain entities are property bags, the Application project references Infrastructure, there's a repository per table, each request is mapped through four DTO types, and every class has a one-implementation interface. What do you flag, in what order, and what does the rewrite look like?

A code review of a cargo-cult Clean Architecture solution: anaemic entities, a broken dependency rule, table-shaped repositories, mapping chains and needless interfaces, ranked by severity with a rewrite and review close-out.

Senior CodeReview Advanced anaemic-domain-model architecture clean-architecture code-review over-engineering repository

🎯 Key points

  • Rank by severity: broken invariants (wrong data) first, then the broken dependency rule, then performance, then ceremony
  • Anaemic entities: data with no behaviour, so business rules are scattered across handlers instead of encapsulated — any handler can put an order into an invalid state
  • Application referencing Infrastructure inverts the dependency rule and couples use cases to EF Core concretes
  • Repository per table ignores aggregates; it splits one consistency boundary across several SaveChanges or transactions
  • Four DTO hops multiply code, maintenance and drift: a rename must be synchronised across every mapping or values silently become defaults; reads should project straight to the response
  • One-implementation interfaces inside a layer add indirection without a boundary; keep them at real seams
  • Rewrite: rich aggregate (private setters, backing fields — EF Core maps them), one repository per aggregate root, port owned by Application, projection queries
  • Close with blocking vs suggested comments, an architecture test and an ADR, not just comments

⏱ 30-second answer

I'd rank findings by impact, not by how ugly they look:

  1. Wrong data: anaemic entities with public setters mean invariants aren't enforced — any handler can set Status = Shipped on an unpaid order. A repository per table splits one aggregate across several saves, risking partial writes.
  2. Broken dependency rule: Application referencing Infrastructure couples use cases to EF Core and makes the "Clean" label false.
  3. Performance and bugs: four DTO mappings per request add allocations and silently drop fields.
  4. Ceremony: one-implementation interfaces everywhere.

The rewrite: a rich aggregate, one repository per aggregate root with the port owned by Application, projection queries for reads, and interfaces only at real boundaries — enforced by an architecture test.

🗣 Full answer (senior)

How I would answer this in an interview

"I'd start by separating what produces wrong data from what is merely heavy. The most serious problem is the anaemic domain: entities with public setters and no behaviour mean the rules live in whichever handler touches the field, so nothing stops a handler setting an unpaid order to Shipped. Close behind is the repository per table: OrderRepository and OrderLineRepository each call SaveChanges, so adding a line and updating the total can half-succeed. Those two findings are blocking, because they can corrupt data.

Next, the dependency rule. Application references Infrastructure, so handlers use the concrete AppDbContext and the Stripe client directly. That's not Clean Architecture any more; it's layering with extra projects. Then there's waste: each request goes Request → Command → Entity → Dto → Response through AutoMapper profiles, which costs allocations and, worse, a renamed property silently maps to null. And every class has an IFoo with one Foo, which doubles the files without creating a single real seam. For example, on [a policy admin system] I reviewed, [a renamed field was dropped by a mapping profile and went unnoticed for two weeks], which is what convinced the team to simplify.

The mistake I see in reviews like this is leaving forty comments of equal weight. I'd mark the first two as blocking, propose the rewrite of one aggregate as a worked example, add an architecture test for the dependency rule, and capture the rest in an ADR so the team simplifies incrementally rather than in a big-bang refactor. The goal isn't purity; it's that the layers protect something."


Code under review

// Domain/Order.cs
public class Order                          // 1 anaemic: public setters, no behaviour
{
    public Guid Id { get; set; }
    public string Status { get; set; } = "Draft";
    public decimal Total { get; set; }
}

// Application/Orders/AddLineHandler.cs
using Infrastructure.Persistence;           // 2 Application -> Infrastructure

public class AddLineHandler(
    IOrderRepository orders,                // 3 repository per table
    IOrderLineRepository lines,
    IMapper mapper,                         // 4 mapping chain
    AppDbContext db) : IAddLineHandler      // 5 one-implementation interface
{
    public async Task<OrderDto> Handle(AddLineCommand cmd)
    {
        var order = await orders.GetAsync(cmd.OrderId);
        var line = mapper.Map<OrderLine>(cmd);
        await lines.AddAsync(line);         // SaveChanges #1
        order.Total += line.Price * line.Qty; // 6 rule in the handler; no status check
        await orders.UpdateAsync(order);    // SaveChanges #2 -> partial write possible
        return mapper.Map<OrderDto>(order); // later mapped again to OrderResponse
    }
}

Findings, by severity

# Severity Finding Why it matters
1, 6 Wrong data Anaemic entity; invariant ("only draft orders change") not enforced; total updated by hand Invalid states reachable from any handler
3 Wrong data Repository per table, two SaveChanges calls Line saved, total not: inconsistent aggregate
2 Design (high) Application references Infrastructure and AppDbContext Dependency rule broken; use cases tied to EF Core concretes
4 Bugs + perf Four-hop mapping via AutoMapper Silent nulls on rename; extra allocations per request
5 Ceremony IAddLineHandler and similar one-implementation interfaces Indirection with no seam; slower navigation

The rewrite

See the code example: an Order aggregate that owns its lines and total, an IOrderRepository port in Application for the aggregate root only, a handler that loads, calls one method and saves once, and a read query that projects straight to the response.

How I'd close the review

Comment Type
Enforce invariants in Order; remove public setters Blocking
One repository per aggregate root, single SaveChangesAsync Blocking
Remove Application → Infrastructure reference; add ArchUnitNET rule Blocking for new code, baseline existing
Replace mapping chain with projection for reads, explicit mapping for writes Suggested, incremental
Drop interfaces without a second implementation or test seam Suggested

I'd follow up with an ADR ("What each layer protects") and a short pairing session on one aggregate.

Production example

After a review like this on a 40-endpoint service, the team rewrote three aggregates over two sprints. Mapping profiles fell from 62 to 9, handler files shrank by about 35%, and a class of production bugs — orders edited after dispatch, about 15 a month — dropped to zero once the invariant moved into the aggregate.

🔍 What the interviewer is checking

Checks that the candidate can review an architecture critically, rank issues by real impact and propose an incremental, convincing rewrite.

Green flags

  • Puts invariant enforcement and partial writes ahead of style issues
  • Explains aggregates as consistency boundaries and one repository per aggregate root
  • Identifies the broken dependency rule and proposes an architecture test
  • Proposes incremental remediation with blocking vs suggested comments

Red flags

  • Only comments on naming and folder structure
  • Proposes a big-bang rewrite
  • Thinks EF Core requires public setters
  • Removes all interfaces including real seams

📚 Learn in depth

1. Why severity order matters

Architecture reviews tempt you to lead with structure. But users feel wrong data first. Rank:

crash / data corruption / security  >  wrong results  >  diagnostics & perf  >  design & ceremony

The anaemic model and table repositories are in the first bucket because they allow invalid states and partial writes.

2. Aggregates vs tables

Table-shaped:                    Aggregate-shaped:
[OrderRepository] -> Orders      [OrderRepository] -> Order (root)
[OrderLineRepository] -> Lines                          +-- Lines (owned)
  two SaveChanges                                       +-- Total (derived)
                                   one SaveChanges = one transaction

An aggregate is a consistency boundary: everything inside changes together in one transaction. A repository per table breaks the boundary, because each repository commits its own part.

3. The dependency rule broken

Intended:  Api -> Application -> Domain        Infrastructure -> Application
Actual:    Application -> Infrastructure  (cycle risk, EF Core everywhere)

The moment Application uses AppDbContext concretely, use cases can't be tested without EF Core, and Infrastructure changes ripple into handlers.

4. The cost of mapping chains

Request → Command → Entity → Dto → Response means four object graphs per call, and convention-based mappers fail silently: rename Qty to Quantity on one side and the value becomes 0 without a compile error. For reads, a single Select projection in the query produces the response directly and only fetches needed columns. For writes, explicit mapping (or a source generator such as Mapperly) gives compile-time safety.

5. Interfaces as seams

An interface is worth it when it marks a seam: a boundary to infrastructure, a place you substitute in tests, or a genuine strategy. IAddLineHandler with one implementation, resolved only by an endpoint, is none of these.

6. Incremental remediation

  1. Add architecture tests with a baseline.
  2. Pick the aggregate with the most bugs; make it rich; collapse its repositories.
  3. Replace read mappings with projections endpoint by endpoint.
  4. Delete one-implementation interfaces as files are touched.

Try it yourself

  1. Write a test that sets order.Status = "Shipped" then adds a line via the current handler; see that it succeeds.
  2. Make the setters private and add AddLine; watch the compiler find every rule-breaking call site.
  3. Simulate a failure between the two SaveChanges calls and inspect the database state.
  4. Rename a property used by an AutoMapper profile and run the app without AssertConfigurationIsValid — note the silent null.
  5. Count interfaces with one implementation using a quick Roslyn script or IDE search.

💻 Code

The rewrite: a rich aggregate, a port for the aggregate root, a handler that saves once, and a read projection.

// Domain/Orders/Order.cs
namespace Shop.Domain.Orders;

public sealed class Order
{
    private readonly List<OrderLine> _lines = [];
    private Order() { }

    public Guid Id { get; private set; } = Guid.NewGuid();
    public OrderStatus Status { get; private set; } = OrderStatus.Draft;
    public IReadOnlyList<OrderLine> Lines => _lines;
    public decimal Total => _lines.Sum(l => l.UnitPrice * l.Quantity); // derived, can't drift

    public static Order Create() => new();

    public Result AddLine(string sku, int quantity, decimal unitPrice)
    {
        if (Status != OrderStatus.Draft) return Result.Fail("Only draft orders can be changed.");
        if (quantity <= 0) return Result.Fail("Quantity must be positive.");
        _lines.Add(new OrderLine(sku, quantity, unitPrice));
        return Result.Ok();
    }
}

public sealed record OrderLine(string Sku, int Quantity, decimal UnitPrice);
public enum OrderStatus { Draft, Placed, Shipped }

public readonly record struct Result(bool Succeeded, string? Error)
{
    public static Result Ok() => new(true, null);
    public static Result Fail(string error) => new(false, error);
}
// Application/Orders/AddLine.cs — no reference to Infrastructure
namespace Shop.Application.Orders;

using Shop.Domain.Orders;

public interface IOrderRepository // one per aggregate root; a real seam to persistence
{
    Task<Order?> GetAsync(Guid id, CancellationToken ct);
    Task SaveChangesAsync(CancellationToken ct); // one transaction for the whole aggregate
}

public sealed record AddLineCommand(Guid OrderId, string Sku, int Quantity, decimal UnitPrice);

public sealed class AddLineHandler(IOrderRepository orders) // no IAddLineHandler: nothing substitutes it
{
    public async Task<Result> HandleAsync(AddLineCommand cmd, CancellationToken ct)
    {
        var order = await orders.GetAsync(cmd.OrderId, ct);
        if (order is null) return Result.Fail("Order not found.");

        var result = order.AddLine(cmd.Sku, cmd.Quantity, cmd.UnitPrice);
        if (result.Succeeded) await orders.SaveChangesAsync(ct);
        return result;
    }
}
// Infrastructure/Queries/OrderSummaryQuery.cs — reads project straight to the response, no mapping chain
namespace Shop.Infrastructure.Queries;

using Microsoft.EntityFrameworkCore;

public sealed record OrderSummaryResponse(Guid Id, string Status, int LineCount, decimal Total);

public sealed class OrderSummaryQuery(ShopDbContext db)
{
    public Task<OrderSummaryResponse?> GetAsync(Guid id, CancellationToken ct) =>
        db.Orders.AsNoTracking()
            .Where(o => o.Id == id)
            .Select(o => new OrderSummaryResponse(
                o.Id, o.Status.ToString(), o.Lines.Count, o.Lines.Sum(l => l.UnitPrice * l.Quantity)))
            .SingleOrDefaultAsync(ct);
}

The EF Core mapping for Lines (OwnsMany or a separate entity with a backing field) lives in an IEntityTypeConfiguration<Order> in Infrastructure, keeping the domain persistence-ignorant.

⚠ Common mistakes

  • Mistake: Leading the review with folder names and interface counts. Why it is wrong: the data-corrupting issues get lost among cosmetic ones. Instead: rank by severity: wrong data, broken rules, performance, ceremony.
  • Mistake: Accepting public setters on entities because "EF Core needs them". Why it is wrong: EF Core materialises through private setters, backing fields and private constructors. Instead: make setters private and expose behaviour methods.
  • Mistake: One repository per table. Why it is wrong: an aggregate's consistency boundary is split across several commits. Instead: one repository per aggregate root, or use DbContext directly in handlers.
  • Mistake: Allowing Application to reference Infrastructure "temporarily". Why it is wrong: temporary references become permanent and spread. Instead: introduce a port and add an architecture test with a baseline.
  • Mistake: Convention-based mapping chains without validation. Why it is wrong: renamed properties silently map to defaults. Instead: project reads in the query; map writes explicitly or with a source generator.
  • Mistake: Demanding a big-bang rewrite in the review. Why it is wrong: it stalls delivery and rarely gets approved. Instead: fix one aggregate as an example and remediate incrementally.
  • Mistake: Deleting every interface. Why it is wrong: some are real seams (persistence, external APIs, time). Instead: keep interfaces at boundaries and remove only those with no seam.

🏛 Senior insight: trade-offs

Cargo-cult Clean Architecture is common because templates make the folders free and the thinking optional. A senior reviewer asks "what does each layer protect?" If the domain protects no invariants, the layering is pure cost. I push for a rich model where rules are complex, simplicity where they aren't, and mechanical enforcement of whatever we keep. I also manage the human side: one worked example beats forty comments, and an ADR turns a review into a team decision.

Option When it fits Cost When not to
Fix in place (rich aggregates, fewer layers) Domain has real rules; team open to change Two or three sprints of incremental work Service scheduled for retirement
Simplify to vertical slices Mostly CRUD with few shared rules Restructuring folders and DI Complex shared invariants
Leave structure, add tests only Low-change legacy area Low Active development where bugs keep appearing

I measure the outcome by bugs in the affected area, mapping profiles and files per feature, and handler test speed.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate says the dependency rule is broken. Why: Checks whether they can describe what a correct Clean Architecture layout looks like.
    How to answer

    Clean Architecture (Robert C. Martin, 2012) arranges code in concentric layers with one rule: source code dependencies point inwards.

    • Domain (centre): entities, value objects, domain events and business rules — no EF Core, no ASP.NET Core.
    • Application: use cases (commands, queries, handlers) plus the interfaces they need, such as IOrderRepository or IEmailSender.
    • Infrastructure: implements those interfaces with EF Core, Azure Service Bus, Blob Storage.
    • Presentation: endpoints and the composition root that wires implementations to interfaces.

    The key move is dependency inversion: the database depends on the domain, not the other way round. The trade-off: testable, technology-independent rules in exchange for more projects, interfaces and mapping — overkill for simple CRUD.

  2. When: Candidate criticises the repository per table. Why: Checks whether they understand repository design and the generic repository anti-pattern.
    How to answer

    A repository gives the domain a collection-like interface for one aggregate root: GetAsync(orderId), Add(order). The domain asks for orders; it doesn't know about SQL, DbContext or tables. That's different from a DAO/table gateway, which mirrors tables with CRUD per table.

    In EF Core, DbContext already is a repository (DbSet<T>) and a unit of work (SaveChanges). So a generic IRepository<T> with GetAll(), Update() and Save() usually adds a layer with no behaviour, and makes things worse:

    • IQueryable<T> GetAll() leaks EF semantics to callers.
    • Save() per repository breaks the unit of work.
    • It invites repositories for child entities, which bypass the aggregate's rules.

    A good repository is narrow and aggregate-specific, takes a CancellationToken and never commits. The trade-off is an abstraction that protects the domain model, against a layer that only renames EF Core.

  3. When: Candidate criticises the mapping chain. Why: Checks whether they can compare hand-written mapping, AutoMapper and Mapperly and know when to project.
    How to answer

    The Mapper pattern keeps two models (entity and DTO) apart by putting the conversion in one place. In .NET 10 there are three common options:

    • Hand-written mapping (extension methods or constructors): explicit, fast, compile-checked. The risk is forgetting a new property.
    • AutoMapper: convention-based run-time mapping with ProjectTo. Since v15.0 (July 2025) it's dual-licensed RPL-1.5/commercial (Lucky Penny Software), free for companies under US$5M revenue.
    • Mapperly: an Apache 2.0 source generator. It writes the mapping code at build time, reports unmapped members as diagnostics, is AOT-safe and can generate IQueryable projections.

    The bigger win is often where you map. Projecting with Select in the query fetches only the needed columns, skips tracking and avoids lazy-loading N+1. Loading entities and mapping them afterwards over-fetches. The trade-off is convenience against explicitness, licence cost and run-time surprises.

🛠 Real-world problems: how you handle them

Orders edited after dispatch because rules lived in handlers
Situation
A [retail order service] built from a Clean Architecture template, [40] endpoints, [4] developers. Warehouse staff reported orders changing after they had been picked.
Signals
About [15] support tickets a month for 'order changed after dispatch'; audit rows showing line additions on `Shipped` orders; occasional orders whose `Total` didn't match their lines.
Investigation
Queried the audit table for changes after dispatch; traced writes in Application Insights to three different handlers that modified lines; found no status check in two of them; found two `SaveChanges` calls per handler via table repositories.
Resolution
Immediately: hotfixed the two handlers with the missing status check and wrapped both saves in one transaction. Then: made `Order` a rich aggregate with private setters and an `AddLine` method enforcing status, derived `Total` from the lines, collapsed `OrderLineRepository` into `OrderRepository` with a single `SaveChangesAsync`, and removed the Application → Infrastructure reference.
Prevention
Domain unit tests for every invariant; ArchUnitNET rules for layer direction and 'no public setters in Domain'; an ADR on aggregate design; a review checklist item asking where each rule lives.

How to tell it (STAR)

**S:** On [our order service], about [15] orders a month were being changed after dispatch. **T:** I was asked to review the code and fix the cause, not just the symptom. **A:** I found the rules lived in three handlers, two without a status check, and table-shaped repositories committing separately. I ranked the review by data impact, rewrote the `Order` aggregate as a worked example, added architecture tests with a baseline, and wrote an ADR the team agreed in a short session. **R:** After-dispatch edits dropped to [zero], mapping profiles went from [62] to [9], and the team applied the same pattern to [two] more aggregates on their own.

↩ Usually asked after

More in Application Architectures

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me