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.
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.
"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 = truedirectly 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
doubleandDateTime.Now, which are wrong-data bugs; then the rules duplicated between the service and the admin controller; then design and naming, likeUpdateSubscription(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
SubscriptionServiceso we know current behaviour. Then move one rule at a time:Pausemoves into the entity, the service method calls it, tests stay green. Replace the booleans with aSubscriptionStatusenum and aMoneyvalue 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."
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();
}
}
| # | 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 |
See the code example: a Subscription with Pause, Resume, ChangePlan and Cancel, a status enum, Money, and a thin handler.
double for money.DateTime.Now in billing logic.PlanCode type, results instead of exceptions.Domain once done.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].
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
double, local time and the generic update bypassRed flags
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.
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.
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.
.IsPaused = and friends; list them.Subscription.Pause(clock), call it from the service; tests stay green.private; the compiler finds anything left.Status via an EF Core migration that computes the new column from the old ones.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.
Reference data, admin CRUD, read models and reporting tables have no behaviour worth encapsulating. A rich model there is ceremony.
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;
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.
I'd rank findings by impact, not by how ugly they look:
Status = Shipped on an unpaid order. A repository per table splits one aggregate across several saves, risking partial writes.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.
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.
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.
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.
Last updated 23 Nov 2026.