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

📚 Interview question

What are feature envy and inappropriate intimacy? How do you spot them in a C# codebase, and how do you fix them by moving behaviour to the data, without ending up with entities that depend on infrastructure?

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.

Mid-Level Theory Intermediate code-quality code-smells encapsulation feature-envy rich-domain-model tell-dont-ask

🎯 Key points

  • Feature envy: a method uses another object's data more than its own; fix with move method (or extract then move) onto the class that owns the data
  • Inappropriate intimacy: two classes reach into each other's internals (public setters, internal collections, friend-like access); envy left unfixed tends to grow into it
  • Both are coupler smells: changes to one class's data ripple into the other, and the logic can only be tested with the other class fully built
  • Tell, don't ask: ask the object to do the work instead of pulling its data out
  • Common .NET form: anaemic entities with services doing all calculations; message chains like order.Customer.Address.State
  • Find them with Find Usages on entity properties, CA1506 class coupling, NDepend/Rider dependency views and duplicated calculations
  • Encapsulate collections (IReadOnlyList over a backing field) and remove public setters; EF Core maps both
  • Move pure domain behaviour only; keep I/O (DbContext, HTTP, email) out of entities; Strategy and mappers separate data from behaviour on purpose

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 reads invoice.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 envies Invoice. Inappropriate intimacy is the two-way, deeper version: classes that know each other's internals. OrderService does order.Lines.Add(...) and then updates order.Total itself, or Shipment reaches into Order to flip a status flag. Change how Order stores 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 exposes IReadOnlyList<OrderLine> and keeps its invariants, like 'total equals the sum of lines', in one place. Message chains such as order.Customer.Address.State are a related sign; often the fix is a method like order.ShippingState() or passing the value in directly.

The mistake I see is moving everything onto the entity, including I/O. An Order.Save() that uses DbContext, or Invoice.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."


Spotting them

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

Fixes

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()

What stays out of the entity

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

Production example

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.

🔍 What the interviewer is checking

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

  • Gives a concrete .NET example (service computing an entity's total)
  • Explains tell, don't ask and encapsulated collections
  • Links the smells to the anaemic domain model
  • Keeps I/O out of entities and mentions domain services for cross-aggregate rules

Red flags

  • Puts DbContext calls or email sending on entities
  • Can't distinguish feature envy from a deliberate Strategy
  • Thinks EF Core requires public setters

📚 Learn in depth

1. Why couplers hurt

Coupling 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).

2. How feature envy turns into inappropriate intimacy

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.

3. Tell, don't ask

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.

4. The anaemic domain model link, and how EF Core helps fix it

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.

5. Finding them

  • Find Usages on an entity's properties in Visual Studio or Rider: many writes from outside the entity mean intimacy.
  • CA1506 class coupling and NDepend's dependency matrix show classes that depend on many others.
  • Duplicated calculations (Sonar duplication report) over the same entity are often envy repeated.
  • Searching for message chains with a regex such as \.\w+\.\w+\.\w+\..

6. Move method mechanics

  1. Extract the envious code into its own method in place.
  2. Check what it uses from this; pass those in as parameters if few.
  3. Use the IDE Move instance method (Rider) or move manually; leave a delegating method in the old place if callers are many.
  4. Inline the delegate later.

7. When separating behaviour from data is right

  • DTOs and mappers: their job is to read data.
  • Strategy/Policy: pricing rules vary independently of the order, so a IPricingPolicy reading the order is deliberate.
  • Cross-aggregate logic: "can this customer place this order" involves two aggregates and belongs in a domain service.
  • Reporting/read models: queries project data; no behaviour needed.

Try it yourself

  1. Find a service method whose first parameter is an entity. Count entity. references versus this./fields.
  2. Move it to the entity and write a unit test for it with no mocks.
  3. Change an entity's List<T> property to a backing field with IReadOnlyList<T>; see what breaks (that is the intimacy).
  4. Make one entity's setters private and count the compile errors: each is a candidate for move method.

💻 Code

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);
});

⚠ Common mistakes

  • Mistake: Moving I/O onto entities (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.
  • Mistake: Exposing 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.
  • Mistake: Calling every Strategy or mapper feature envy. Why it is wrong: Some behaviour is deliberately separated because it varies independently. Instead: Ask whether the logic changes for the same reason as the data.
  • Mistake: Fixing message chains by adding a wrapper method on every class in the chain. Why it is wrong: You get a bloated middle man everywhere. Instead: Hide the delegate only where callers really need it, or pass the needed value in.
  • Mistake: Keeping entities anaemic in the belief that EF Core needs public setters and mutable lists. Why it is wrong: EF Core materialises through private setters, private constructors and backing fields, and maps value objects as complex types; the belief is outdated and pushes all behaviour into services (feature envy at scale). Instead: Use private setters, encapsulated collections and complex types, and put behaviour on the entity.
  • Mistake: Using 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.
  • Mistake: Moving cross-aggregate logic onto one entity. Why it is wrong: Order now loads and mutates Customer, which breaks aggregate boundaries. Instead: Put logic that spans aggregates in a domain service.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions anaemic entities or moving behaviour into the domain Why: Checks whether they can move a codebase towards a richer model without over-engineering
    How to answer

    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.

  2. When: Candidate says some logic belongs in a service rather than the entity Why: Checks the difference between application services, domain services and entity behaviour
    How to answer

    These are three layers of responsibility:

    • An application service (Fowler's service layer) runs one use case. It loads aggregates through repositories, calls domain logic, commits the unit of work and publishes events. It handles transactions, authorisation and mapping, but holds no business rules.
    • A domain service holds stateless business logic that doesn't belong to one entity, often spanning aggregates (a funds transfer, a pricing policy). It's named in domain language and knows nothing about HTTP or EF Core.
    • Entities and value objects own their own invariants (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.

🛠 Real-world problems: how you handle them

Four services computing invoice totals four slightly different ways
Situation
A billing platform for [an Australian SaaS company], [~15,000] invoices a month. Invoice totals were calculated in `InvoiceService`, `CreditNoteService`, `StatementService` and a PDF renderer, each reading `Invoice` fields directly.
Signals
Customers reported [one-cent] differences between the PDF and the statement; finance raised [a handful of] reconciliation tickets a month; changing the GST-free rule needed edits in four files and one was missed.
Investigation
Searched for reads of `DiscountRate` and `Lines` outside `Invoice` with Rider's *Find Usages* and found [11] places. Compared the four calculations side by side: two rounded per line, two rounded the total, one used `MidpointRounding.ToEven` (the default). Checked git history: every GST change in [the past year] had touched all four.
Resolution
Immediate: patched the renderer to match the invoice calculation agreed with finance. Real fix: added `Invoice.Total()` and `InvoiceLine.Net` with the agreed rounding rule, covered by unit tests for edge cases (GST-free, discounts, half-cent values), then replaced each service's calculation with a call to it, one PR per service. Encapsulated `Lines` behind `AddLine`/`RemoveLine`.
Prevention
Removed public setters from `Invoice`; an architecture test (NetArchTest) fails if classes outside the domain set `Invoice` properties. Added a review checklist item: 'Is this logic using another object's data? Should it live there?'

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.

More in Code Smells

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me