Covers the feature envy and inappropriate intimacy coupler smells, how they show up in .NET (service methods reading another object's fields, classes reaching into each other's internals, message chains), and how to fix them with move method, tell-don't-ask and encapsulation while keeping entities free of infrastructure.
Feature envy is a method that is more interested in another class's data than its own: InvoiceService.CalculateTotal(invoice) reading ten properties of Invoice. Inappropriate intimacy is two classes that know each other's internals: one mutates the other's List<T> directly or depends on its private-ish state.
Both are coupler smells: change the data and the other class breaks. The fix is move method and tell, don't ask: put the behaviour on the class that owns the data (invoice.Total()), encapsulate collections behind methods, and drop public setters.
The trade-off: move pure domain logic, not I/O. An entity that calls DbContext or sends email has swapped one smell for a worse one.
"Feature envy is when a method spends most of its time with someone else's data. The classic .NET example is a service method like
InvoiceService.CalculateTotal(Invoice invoice)that readsinvoice.Lines, each line's price and quantity, the discount and the customer's tax status, and owns none of it. The method is in the wrong place; it enviesInvoice. Inappropriate intimacy is the two-way, deeper version: classes that know each other's internals.OrderServicedoesorder.Lines.Add(...)and then updatesorder.Totalitself, orShipmentreaches intoOrderto flip a status flag. Change howOrderstores lines and both break.The fix is mostly move method plus encapsulation. I extract the envious part, move it to the class that owns the data, and replace 'ask for data, decide, write it back' with 'tell the object what to do':
invoice.Total(),order.AddLine(product, qty),order.MarkShipped(clock). The entity exposesIReadOnlyList<OrderLine>and keeps its invariants, like 'total equals the sum of lines', in one place. Message chains such asorder.Customer.Address.Stateare a related sign; often the fix is a method likeorder.ShippingState()or passing the value in directly.The mistake I see is moving everything onto the entity, including I/O. An
Order.Save()that usesDbContext, orInvoice.SendEmail(), makes the domain depend on infrastructure and hard to test. Pure calculations and state transitions belong on the entity; orchestration, persistence and messaging stay in the handler. And not every separation is envy: a Strategy or a mapper reads another object's data on purpose. The test is whether the logic changes for the same reason as the data."
| Signal | Smell |
|---|---|
A method references other.X more than this |
Feature envy |
| Service methods take an entity as the first parameter and read many of its properties | Feature envy (anaemic model) |
| Class A modifies class B's collection or fields directly | Inappropriate intimacy |
| Two classes always change together, and each uses the other's internals | Inappropriate intimacy |
a.B.C.D.Value |
Message chain (often accompanies envy) |
internal or InternalsVisibleTo used to let one class poke another |
Possible intimacy |
| Smell | Refactoring | Result |
|---|---|---|
| Feature envy | Extract method, then move method | invoice.Total() |
| Intimacy via public setters | Remove setter, add intention-revealing method | order.MarkShipped(at) |
| Intimacy via collections | Encapsulate collection | IReadOnlyList<OrderLine> Lines + AddLine |
| Bidirectional dependency | Change to unidirectional, or extract shared class | Dependency flows one way |
| Message chain | Hide delegate | order.ShippingState() |
| Belongs on the entity | Stays in handler / service |
|---|---|
| Calculations from its own data | Database access (DbContext) |
| State transitions and invariants | HTTP calls, email, queues |
| Validation of its own rules | Orchestration across aggregates |
| Domain events raised | Transactions and retries |
In a billing system where invoice totals were computed in four services, each slightly differently, moving the calculation onto Invoice.Total() typically removes a class of rounding defects at once (one GST rounding rule instead of four) and makes the calculation unit-testable without any mocks.
Checks that the candidate understands coupling smells, can apply move method and tell-don't-ask, and knows where to stop so the domain stays free of infrastructure.
Green flags
Red flags
DbContext calls or email sending on entitiesCoupling is how much one module must know about another. Feature envy and intimacy create knowledge coupling: the envious class knows the other's data layout.
Before After
InvoiceService --reads--> Invoice InvoiceService --calls--> Invoice.Total()
(Lines, Discount, (knows one method)
Customer.TaxStatus,
Line.UnitPrice ...)
If Invoice changes how it stores discounts, the left side breaks in every service that read it; the right side changes in one place. Left unfixed, this costs you twice: maintenance (every data change ripples) and testing (to test the calculation you must build a whole Invoice graph and often a service with mocked dependencies, instead of calling one method on a small object).
The two smells usually arrive in sequence:
1. Service reads Invoice's data to calculate something -> feature envy (one-way, read-only)
2. Service writes the result back: invoice.Total = ... -> now it maintains Invoice's invariant
3. Service adds to invoice.Lines directly -> it depends on Invoice's internals
4. Invoice starts calling back into the service -> two-way: inappropriate intimacy
Each step is a small, reasonable-looking change. By step 4 neither class can change its internals without the other. Fixing envy early (move the calculation onto Invoice) removes the reason for steps 2 to 4.
The principle (from Andy Hunt and Dave Thomas, and the Law of Demeter before it): instead of asking an object for its state and making a decision about it, tell the object what you want and let it decide. It keeps data and the rules over that data together, which is what encapsulation means. The Law of Demeter's "only talk to your immediate friends" is the rule that message chains break.
In many .NET apps entities are EF Core POCOs with public get; set; on everything, and all behaviour lives in services. That design is feature envy at scale. Developers often keep it because they believe EF Core needs public setters and a mutable List<T>. It doesn't. EF Core 10 supports the rich shape directly:
| Anaemic (what people assume EF needs) | Rich (what EF Core supports) | How EF handles it |
|---|---|---|
public decimal DiscountRate { get; set; } |
{ get; private set; } |
EF sets properties through private setters when materialising |
public List<InvoiceLine> Lines { get; set; } |
private readonly List<InvoiceLine> _lines; + IReadOnlyList<InvoiceLine> Lines => _lines; |
Backing field discovered by convention; UsePropertyAccessMode(PropertyAccessMode.Field) makes EF read/write the field |
| Public parameterless constructor used by callers | Private parameterless constructor for EF + public factory or constructor with rules | EF can use a private constructor or one whose parameters match mapped properties |
| Money as two loose columns | ComplexProperty(i => i.Refunded) |
Value object mapped into the owner's table |
The transition is mechanical: make a setter private, compile, and the errors show every place that was envious or intimate; move each of those pieces of logic onto the entity as a method.
\.\w+\.\w+\.\w+\..this; pass those in as parameters if few.IPricingPolicy reading the order is deliberate.entity. references versus this./fields.List<T> property to a backing field with IReadOnlyList<T>; see what breaks (that is the intimacy).Before and after: totals and line management move from the service onto Invoice; I/O stays in the handler.
// Before: feature envy and intimacy
namespace Billing.Before;
public class Invoice
{
public Guid Id { get; set; }
public List<InvoiceLine> Lines { get; set; } = [];
public decimal DiscountRate { get; set; }
public decimal Total { get; set; }
public bool GstFree { get; set; }
}
public class InvoiceLine { public decimal UnitPrice { get; set; } public int Quantity { get; set; } }
public class InvoiceService(BillingDbContext db)
{
public async Task AddLine(Guid invoiceId, decimal price, int qty, CancellationToken ct)
{
var invoice = await db.Invoices.Include(i => i.Lines).SingleAsync(i => i.Id == invoiceId, ct);
invoice.Lines.Add(new InvoiceLine { UnitPrice = price, Quantity = qty }); // reaches into the list
invoice.Total = CalculateTotal(invoice); // keeps Invoice's invariant for it
await db.SaveChangesAsync(ct);
}
// Envy: uses only Invoice's data
private static decimal CalculateTotal(Invoice i)
{
var net = i.Lines.Sum(l => l.UnitPrice * l.Quantity) * (1 - i.DiscountRate);
return i.GstFree ? net : Math.Round(net * 1.10m, 2, MidpointRounding.AwayFromZero);
}
}
// After: tell, don't ask; invariants live with the data
namespace Billing.After;
public sealed record InvoiceLine(decimal UnitPrice, int Quantity)
{
public decimal Net => UnitPrice * Quantity;
}
public sealed class Invoice
{
private const decimal GstRate = 0.10m;
private readonly List<InvoiceLine> _lines = [];
public Guid Id { get; private set; } = Guid.CreateVersion7();
public decimal DiscountRate { get; private set; }
public bool GstFree { get; private set; }
public IReadOnlyList<InvoiceLine> Lines => _lines; // no outside mutation
public void AddLine(decimal unitPrice, int quantity)
{
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(quantity);
_lines.Add(new InvoiceLine(unitPrice, quantity));
}
// Pure domain calculation: no DbContext, no clock, no I/O
public decimal Total()
{
var net = _lines.Sum(l => l.Net) * (1 - DiscountRate);
return GstFree ? net : Math.Round(net * (1 + GstRate), 2, MidpointRounding.AwayFromZero);
}
}
// The handler keeps orchestration and persistence
public sealed class AddInvoiceLineHandler(BillingDbContext db)
{
public async Task HandleAsync(Guid invoiceId, decimal price, int qty, CancellationToken ct)
{
var invoice = await db.Invoices.SingleAsync(i => i.Id == invoiceId, ct);
invoice.AddLine(price, qty);
await db.SaveChangesAsync(ct);
}
}
// EF Core: map the backing field so the entity stays encapsulated
modelBuilder.Entity<Invoice>(e =>
{
e.OwnsMany(i => i.Lines, l => l.WithOwner());
e.Navigation(i => i.Lines).UsePropertyAccessMode(PropertyAccessMode.Field);
});
invoice.Save(), order.SendConfirmation()). Why it is wrong: The domain now depends on infrastructure and can't be unit tested without it. Instead: Move pure calculations and state changes; keep persistence and messaging in handlers.List<T> with a public setter. Why it is wrong: Any class can add or remove items and skip invariants. Instead: Expose IReadOnlyList<T> over a backing field and add intention-revealing methods.InternalsVisibleTo to let production classes poke at each other. Why it is wrong: It formalises inappropriate intimacy. Instead: Reserve it for test assemblies; redesign the API between the classes.Order now loads and mutates Customer, which breaks aggregate boundaries. Instead: Put logic that spans aggregates in a domain service.These smells are where clean code and domain modelling meet. Fixing feature envy one method at a time is how a team moves from an anaemic model to a rich one without a rewrite, and each move makes a rule testable without mocks. I prioritise envious code that is duplicated: four services each computing invoice totals is four places for GST rounding to disagree, which is a correctness risk, not just style.
I also keep the boundary clear: entities own their invariants; handlers own orchestration, transactions and I/O; domain services own rules spanning aggregates. That rule settles most review debates quickly.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Move method onto entity | Logic uses only that entity's data | Small, mechanical | Logic needs I/O or other aggregates |
| Domain service | Rule spans two aggregates | One more class | Logic belongs to one entity |
| Strategy/policy object | Rule varies independently (per region, per customer tier) | Interface + registrations | Only one variant exists |
| Leave in service | Read-only reporting or mapping | None | Logic enforces invariants |
In an anemic domain model, entities are property bags with public getters and setters, and all business rules live in service classes that read and set those properties. In a rich domain model, entities own their behaviour: state is private, changes happen through methods like order.Pay(amount) that enforce invariants, and services only orchestrate (load, call, save). Anemic models scatter and duplicate rules, let any code put objects into invalid states, and are hard to test without a database. They are acceptable for simple CRUD or reporting with few rules. Move towards a richer model incrementally: make setters private, move one rule at a time into the entity, protect collections, and use value objects, guided by where bugs actually occur.
These are three layers of responsibility:
order.Submit()), and they come first.When everything goes into a fat OrderService, entities become property bags: the anaemic domain model. Controllers should only translate HTTP. The trade-off is richer models and clear boundaries against more types and more thought about where each rule lives.
How to tell it (STAR)
**S:** At [company] invoice totals were calculated in four different services, each reaching into `Invoice`'s fields, and they disagreed by a cent in some cases, causing [N] finance reconciliation tickets a month. **T:** I was asked to fix the discrepancy and make sure it couldn't come back. **A:** I found all [11] places that read invoice internals, agreed the rounding rule with finance, and moved the calculation onto `Invoice.Total()` with unit tests for the edge cases. Then I replaced each service's copy with a call, one PR at a time, and encapsulated the lines collection. **R:** The reconciliation tickets dropped to [zero], and the next GST-related change was a [one-file] edit instead of four.
Last updated 23 Nov 2026.