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

📚 Interview question

Code review: a Subscription class has only public getters and setters, and a SubscriptionService holds every rule for upgrading, pausing and cancelling. What problems do you flag, in what order, and how do you refactor it towards a rich domain model step by step?

Covers reviewing an anaemic domain model (public setters, rules in a service), ranking the findings by severity, and refactoring incrementally to a rich model with behaviour methods, value objects and tests.

Senior CodeReview Advanced anaemic-domain-model architecture code-review domain-driven-design ef-core refactoring

🎯 Key points

  • Anaemic domain model (Fowler): data classes with setters, behaviour in services; invariants can be bypassed
  • Rank findings: wrong data (invariants bypassable, money as double, local time) before design (naming, duplication)
  • Public setters let any code put a Subscription into an invalid state (Paused and Cancelled at once)
  • Replace state flags with one status enum and an explicit transition table agreed with the domain expert; every transition is a method
  • Refactor incrementally: characterisation tests first, then move one rule at a time into the entity
  • Run the full unit and integration suite after every moved rule (one rule per PR, CI green before merge); add a test per transition, allowed and rejected
  • Make setters private only after every caller uses the new methods; EF Core still maps private setters
  • Service shrinks to orchestration; not every model needs to be rich (CRUD areas can stay anaemic deliberately)

⏱ 30-second answer

This is an anaemic domain model: the Subscription is a bag of data and the rules live in SubscriptionService, so any code can bypass them by setting properties. I rank findings by impact: first invalid states and wrong data (setters allow paused-and-cancelled, money as double, local DateTime), then duplicated rules across callers, then naming and design (UpdateSubscription, boolean flags instead of a status).

The refactor is incremental: add characterisation tests around the service, move one rule at a time into behaviour methods (Upgrade, Pause, Cancel) on the entity, introduce value objects (Money, BillingPeriod) and a single status enum, then make the setters private once no caller uses them. The service shrinks to load, call, save. The trade-off: some churn now, in exchange for one place where rules live.

🗣 Full answer (senior)

How I would answer this in an interview

"The headline finding is that this is an anaemic domain model. The entity has no behaviour and the rules live in a service, so they only hold if every caller goes through that service. In practice they don't: an admin endpoint or an import job sets IsCancelled = true directly and skips the refund rule. So my first comment isn't about style; it's that the code allows states the business says are impossible.

For example, at [company] we had a [subscription billing] service shaped like this, and the first thing I did was query production for impossible states. We found [~300] subscriptions that were both paused and cancelled, and [a few dozen] with a next billing date in the past. That turned the review from 'I prefer rich models' into 'this is costing us refunds'. I'd rank the findings: setters that allow invalid states, money as double and DateTime.Now, which are wrong-data bugs; then the rules duplicated between the service and the admin controller; then design and naming, like UpdateSubscription(dto) and three booleans that should be one status.

The refactor has to be incremental, because a big-bang rewrite of a billing model is how you break billing. I'd start with characterisation tests around SubscriptionService so we know current behaviour. Then move one rule at a time: Pause moves into the entity, the service method calls it, tests stay green. Replace the booleans with a SubscriptionStatus enum and a Money value object. When no caller sets properties directly any more, which the compiler tells you once you make the setters private, lock them down. EF Core still maps private setters, so persistence doesn't change. I'd mark the invalid-state issues as blocking and the naming as suggestions. I'd also say plainly that not everything needs this: if a part of the system is just CRUD, an anaemic model there is a fine, deliberate choice."


Code under review

public class Subscription
{
    public int Id { get; set; }
    public string Plan { get; set; }              // 1 "basic" | "pro" | "Pro "?
    public double MonthlyPrice { get; set; }      // 2 money as double
    public bool IsPaused { get; set; }            // 3 three flags = 8 combinations
    public bool IsCancelled { get; set; }
    public bool IsTrial { get; set; }
    public DateTime NextBillingDate { get; set; } // 4 local time
}

public class SubscriptionService(AppDbContext db)
{
    public async Task Pause(int id)
    {
        var s = await db.Subscriptions.FindAsync(id);
        if (s.IsCancelled) throw new Exception("Cancelled");  // 5 rule lives here only
        s.IsPaused = true;
        s.NextBillingDate = DateTime.Now.AddMonths(1);       // 6 DateTime.Now
        await db.SaveChangesAsync();
    }

    public async Task UpdateSubscription(SubscriptionDto dto) // 7 generic update bypasses all rules
    {
        var s = await db.Subscriptions.FindAsync(dto.Id);
        s.Plan = dto.Plan; s.MonthlyPrice = dto.MonthlyPrice;
        s.IsPaused = dto.IsPaused; s.IsCancelled = dto.IsCancelled;
        await db.SaveChangesAsync();
    }
}

Findings, by severity

# Severity Finding Fix
7, 3 Wrong data Generic update and public setters allow paused + cancelled, trial + cancelled Behaviour methods, one status enum, private setters
2 Wrong data double money gives rounding errors in billing decimal inside a Money value object
4, 6 Wrong data DateTime.Now on a server in UTC vs customer in AEST; untestable DateTimeOffset + TimeProvider
5 Wrong data Rules only in one service method; other paths skip them Rules on the entity
— Diagnostics throw new Exception("Cancelled"), null not checked after FindAsync Domain results with codes; 404 handling
1 Design Stringly typed plan PlanCode value object or enum
7 Design UpdateSubscription is not in the business language Intention-revealing commands

The rewrite

See the code example: a Subscription with Pause, Resume, ChangePlan and Cancel, a status enum, Money, and a thin handler.

How I'd close the review

  • Blocking: the generic update endpoint and public setters (invalid states exist in production); double for money.
  • Blocking: DateTime.Now in billing logic.
  • Suggested: naming, PlanCode type, results instead of exceptions.
  • Plan: characterisation tests this sprint, then one rule per PR; an architecture test banning public setters in Domain once done.

Production example

Over [four sprints] we moved [11] rules into the Subscription entity in [14] small PRs. A data fix repaired the [~300] invalid rows, the impossible-state query has returned [zero] since, and refund tickets about "charged after cancelling" fell from [~25 a month to 2].

🔍 What the interviewer is checking

Checks that the candidate can spot an anaemic model, explain its real-world cost, rank review findings, and lead a safe incremental refactor.

Green flags

  • Leads with invalid states and wrong data, not style
  • Spots money as double, local time and the generic update bypass
  • Proposes characterisation tests and one-rule-at-a-time refactoring
  • Knows EF Core maps private setters and plans the data migration

Red flags

  • Proposes a full rewrite
  • Only comments on naming
  • Wants every class rich, including reference data

📚 Learn in depth

1. Why anaemic models happen

  • ORMs and scaffolding generate classes with public setters.
  • Layered tutorials put "business logic" in a service layer.
  • DTOs and entities are the same class, so setters are needed for binding.

Fowler called it an anti-pattern because you pay for an object model (mapping, identity) without getting encapsulation: it is a transaction script in disguise.

2. State explosion

Three booleans: IsTrial, IsPaused, IsCancelled  =>  2^3 = 8 combinations
Valid business states: Trial, Active, Paused, Cancelled  =>  4
4 invalid combinations are representable, and the code must defend against them everywhere.

One enum plus transition methods makes invalid combinations unrepresentable.

3. Transitions as a table

            Pause    Resume   Cancel   ChangePlan
Trial       ✗        ✗        ✓        ✓ (ends trial)
Active      ✓        ✗        ✓        ✓
Paused      ✗        ✓        ✓        ✗
Cancelled   ✗        ✗        ✗        ✗

Each cell is a rule; each ✓ is a method that also updates billing dates. This table is what you agree with the domain expert.

4. Incremental refactoring recipe

  1. Characterisation tests over the service (Testcontainers + real SQL Server, or the entity in memory).
  2. Find all writers: search for .IsPaused = and friends; list them.
  3. Move one rule: add Subscription.Pause(clock), call it from the service; tests stay green.
  4. Redirect callers: change each writer to call the method.
  5. Tighten: make that setter private; the compiler finds anything left.
  6. Replace flags with Status via an EF Core migration that computes the new column from the old ones.
  7. Repeat, one PR per rule.

5. Persistence does not have to change much

EF Core maps private setters, private constructors and backing fields. Converting three booleans to one status needs a migration with a data update (UPDATE ... SET Status = CASE ...), and possibly keeping the old columns for one release for rollback.

6. When anaemic is fine

Reference data, admin CRUD, read models and reporting tables have no behaviour worth encapsulating. A rich model there is ceremony.

Try it yourself

  1. Write a SQL query that finds impossible flag combinations in one of your tables.
  2. Draw the transition table for one entity with a domain expert.
  3. Move one rule into an entity behind characterisation tests and make the setter private.
  4. Add a NetArchTest or ArchUnitNET rule that fails on public setters in the Domain namespace.

💻 Code

The refactored model: one status, value objects, behaviour methods, a thin handler.

namespace Billing.Domain;

public enum SubscriptionStatus { Trial, Active, Paused, Cancelled }
public enum PlanCode { Basic, Pro, Team }

public sealed record Money(decimal Amount, string Currency = "AUD");

public sealed record DomainError(string Code, string Message);

public sealed class Subscription
{
    private Subscription() { } // EF Core

    public Subscription(PlanCode plan, Money price, DateTimeOffset now)
    {
        Plan = plan;
        MonthlyPrice = price;
        Status = SubscriptionStatus.Trial;
        NextBillingAt = now.AddDays(14);
    }

    public int Id { get; private set; }
    public PlanCode Plan { get; private set; }
    public Money MonthlyPrice { get; private set; } = null!;
    public SubscriptionStatus Status { get; private set; }
    public DateTimeOffset? NextBillingAt { get; private set; }
    public DateTimeOffset? CancelledAt { get; private set; }

    public DomainError? Pause(DateTimeOffset now)
    {
        if (Status != SubscriptionStatus.Active) return new("subscription.cannot_pause", $"Cannot pause a {Status} subscription.");
        Status = SubscriptionStatus.Paused;
        NextBillingAt = null; // no billing while paused
        return null;
    }

    public DomainError? Resume(DateTimeOffset now)
    {
        if (Status != SubscriptionStatus.Paused) return new("subscription.not_paused", "Only paused subscriptions can resume.");
        Status = SubscriptionStatus.Active;
        NextBillingAt = now.AddMonths(1);
        return null;
    }

    public DomainError? ChangePlan(PlanCode plan, Money price)
    {
        if (Status is SubscriptionStatus.Paused or SubscriptionStatus.Cancelled)
            return new("subscription.cannot_change_plan", $"Cannot change plan while {Status}.");
        (Plan, MonthlyPrice) = (plan, price);
        if (Status == SubscriptionStatus.Trial) Status = SubscriptionStatus.Active; // choosing a plan ends the trial
        return null;
    }

    public DomainError? Cancel(DateTimeOffset now)
    {
        if (Status == SubscriptionStatus.Cancelled) return new("subscription.already_cancelled", "Already cancelled.");
        Status = SubscriptionStatus.Cancelled;
        CancelledAt = now;
        NextBillingAt = null;
        return null;
    }
}
namespace Billing.Application;

using Billing.Domain;
using Microsoft.EntityFrameworkCore;

// The service is now orchestration only.
public sealed class PauseSubscriptionHandler(BillingDbContext db, TimeProvider clock)
{
    public async Task<DomainError?> HandleAsync(int id, CancellationToken ct)
    {
        var sub = await db.Subscriptions.SingleOrDefaultAsync(s => s.Id == id, ct);
        if (sub is null) return new("subscription.not_found", "Not found.");

        var error = sub.Pause(clock.GetUtcNow());
        if (error is null) await db.SaveChangesAsync(ct);
        return error;
    }
}
-- Migration data step: three flags to one status (keep old columns one release for rollback).
UPDATE billing.Subscriptions
SET Status = CASE
    WHEN IsCancelled = 1 THEN 'Cancelled'
    WHEN IsPaused = 1 THEN 'Paused'
    WHEN IsTrial = 1 THEN 'Trial'
    ELSE 'Active' END;

⚠ Common mistakes

  • Mistake: Reviewing it as a style preference ("I like rich models"). Why it is wrong: the team hears opinion and ignores it. Instead: show the concrete risk: query production for impossible states.
  • Mistake: A big-bang rewrite of the model. Why it is wrong: billing breaks and the PR is unreviewable. Instead: characterisation tests, then one rule per PR.
  • Mistake: Moving rules without re-running regression tests each time. Why it is wrong: a moved rule can subtly change behaviour (a date calculated from local time instead of UTC, an exception type callers relied on) and nobody notices until billing runs. Instead: the characterisation and integration suites run in CI on every PR; each moved rule gets its own unit tests before the old code is deleted.
  • Mistake: Making setters private first. Why it is wrong: hundreds of compile errors and a stalled refactor. Instead: add methods and redirect callers first; lock setters last.
  • Mistake: Moving rules into the entity but keeping the generic update endpoint. Why it is wrong: the bypass still exists. Instead: replace it with intention-revealing commands.
  • Mistake: Implementing transitions ad hoc, method by method, without an agreed state model. Why it is wrong: gaps appear (can a trial be paused? what happens to the billing date on resume?) and side effects are forgotten, so new invalid states creep in. Instead: agree the full transition table with the domain expert, implement each cell as a method that also updates dependent fields, and test both allowed and rejected transitions.
  • Mistake: Injecting repositories or services into the entity to make it "rich". Why it is wrong: the domain gains infrastructure dependencies. Instead: the handler passes in what the entity needs (time, prices).
  • Mistake: Converting flags to a status without a data migration plan. Why it is wrong: existing invalid rows break the new rules on load. Instead: find and fix invalid rows first, keep old columns for one release.
  • Mistake: Insisting every class become rich. Why it is wrong: reference data and CRUD areas gain nothing. Instead: target the entities with real rules and lifecycle.

🏛 Senior insight: trade-offs

The point of the review is to move the team from "rules held by convention" to "rules held by the compiler". Evidence wins that argument: one query that finds impossible states in production is worth more than any appeal to DDD books. The refactor is then a sequence of safe, small steps, which is also how you keep the team on board.

Approach When it fits Cost When not to
Incremental move to rich model Entities with lifecycle and rules, live system Several sprints of small PRs Pure CRUD areas
Keep anaemic + transaction scripts Simple rules, reporting, admin data Rules held by convention Rules duplicated across paths
Rewrite the module Model is beyond repair and well tested from outside High risk and cost Without characterisation tests

I measure progress by the number of public setters in the domain project and by the impossible-state query returning zero.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate talks about anaemic models in a Clean Architecture solution. Why: Checks the wider review of a Clean Architecture codebase.
    How to 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.

  2. When: Candidate says the service asks for data and decides, instead of telling the entity. Why: Checks Tell, Don't Ask in domain design.
    How to answer

    Tell, Don't Ask means you tell an object what you want done, and the object decides how, using its own data. Instead of a service doing if (order.Status == Pending && !order.IsPaid) order.Status = Cancelled;, you call order.Cancel(), and the order enforces the rule. That keeps invariants in one place, removes duplicated checks across services and moves you from an anaemic model towards a rich one. It applies to behaviour; for reading data to display or report, querying is exactly right.

  3. When: Candidate proposes behaviour methods and domain errors. Why: Checks they can implement an aggregate that enforces invariants.
    How to answer

    The aggregate owns its rules. I give Order a private constructor and a static factory Order.Create(customerId, address) that validates and returns a Result<Order>. State has private setters; lines live in a private List<OrderLine> exposed as IReadOnlyCollection. Changes happen only through behaviour methods in the business language (AddLine, Submit, Cancel) that check invariants and return a Result with a domain error (Order.AlreadySubmitted) for expected rule violations; exceptions are kept for bugs.

    EF Core 10 maps it through backing fields and a private parameterless constructor, with a rowversion on the root. The application handler stays thin: load, call one method, translate the Result to ProblemDetails, save. The trade-off: a little more code, but every rule is testable in milliseconds with no database.

🛠 Real-world problems: how you handle them

Customers charged after cancelling because a generic update skipped the rules
Situation
A [SaaS subscription] platform with [~40,000] active subscriptions; rules lived in `SubscriptionService`, but an admin 'edit subscription' screen saved the entity directly through a generic update.
Signals
Refund tickets 'charged after cancelling' at [~25 a month]; billing job logs showed charges on rows with `IsCancelled = 1` and `NextBillingDate` set; a query found [~300] paused-and-cancelled rows.
Investigation
Queried for impossible flag combinations, joined them to the audit log to find which endpoint wrote them (the admin generic update), and listed every writer of the flags via code search.
Resolution
Immediately made the billing job skip any row with `IsCancelled = 1` and repaired invalid rows with a data fix. Then refactored incrementally: characterisation tests, behaviour methods on `Subscription`, a status enum with a migration, intention-revealing admin commands, and private setters.
Prevention
Architecture test banning public setters in the Domain project, a nightly impossible-state query with an alert, and a review checklist item for generic update endpoints.

How to tell it (STAR)

**S:** At [company], we were refunding [about 25] customers a month who were charged after cancelling. **T:** In code review of [a related change] I flagged the anaemic Subscription model and was asked to [fix the root cause]. **A:** I ran a query that found [~300] impossible subscription states, traced them to a generic admin update, shipped a guard in the billing job the same day, then led an incremental refactor over [four sprints]: characterisation tests, one rule per PR, a status enum, and private setters. **R:** Refund tickets fell to [~2 a month], the impossible-state query has stayed at zero, and the team adopted the no-public-setters rule for the domain.

More in Domain-Driven Design

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me