Skip to content

Feature Envy: when a method lives in the wrong class

Feature Envy is a code smell where a method reads and computes mostly on another object's data, signalling that the logic belongs next to that data.

6 min readCode smellCoupling

Feature Envy shows up when a method spends most of its time reaching into another object: reading its fields, calling its getters, chaining through its collaborators, then doing arithmetic on what it found. The method sits in one class, but its interest is clearly elsewhere. The cost is coupling. The envious method depends on the internal shape of the other class, so a rename or a new field there breaks code far away. The class that owns the data stays a passive bag of fields, and the rules about that data end up scattered across services, controllers and helpers. The fix is usually simple: move the behaviour to where the data lives. The hard part is noticing it, because envious code often looks tidy and passes every test.

Signs

How to spot it in a review.

  • A method reads four or more fields or getters from one parameter and touches few or none of its own class's fields.
  • The same calculation on another object's data is repeated in several services or controllers.
  • Chains like item.supplier.leadTimeDays appear inside a method that has nothing to do with suppliers.
  • The other class is mostly getters and setters with no real behaviour of its own.
  • Changing a field name in one class forces edits in an unrelated service that only uses it for a calculation.

What it looks like

A typical case, in three languages.

interface Supplier {
  name: string;
  leadTimeDays: number;
}

class StockItem {
  constructor(
    public readonly sku: string,
    public onHand: number,
    public reserved: number,
    public averageDailyDemand: number,
    public safetyStockDays: number,
    public readonly supplier: Supplier,
    public readonly caseSize: number,
  ) {}
}

class ReorderPlanner {
  constructor(private readonly reviewPeriodDays: number) {}

  planOrder(item: StockItem): number {
    const available = item.onHand - item.reserved;
    const coverDays = item.supplier.leadTimeDays + item.safetyStockDays;
    const reorderPoint = Math.ceil(item.averageDailyDemand * coverDays);
    if (available > reorderPoint) {
      return 0;
    }
    const target = Math.ceil(
      item.averageDailyDemand * (coverDays + this.reviewPeriodDays),
    );
    const shortfall = target - available;
    return Math.ceil(shortfall / item.caseSize) * item.caseSize;
  }
}

const planner = new ReorderPlanner(7);
const brakePads = new StockItem(
  "BRK-2210", 40, 12, 6.5, 3,
  { name: "Kessler Parts", leadTimeDays: 5 }, 12,
);
console.log(planner.planOrder(brakePads)); // 72

In this warehouse service, planOrder touches seven pieces of StockItem data and exactly one of its own: reviewPeriodDays. Available stock, reorder point and case rounding are all facts about the item. Extract them into methods such as available(), reorderPoint() and roundUpToCase(units), move those onto StockItem, and give it leadTimeDays() so callers stop walking through supplier. The planner then shrinks to one rule it genuinely owns: how far ahead to order, passed in as the review period.

Why it happens

How code ends up like this.

  • Data classes were designed first as plain records, and behaviour was added later wherever the developer happened to be working.
  • A service layer convention pushes all logic into services, leaving domain objects as field containers.
  • A quick fix was written at the call site under time pressure, then copied to a second and third caller.
  • The other class belongs to a different team or module, so adding code there felt like more effort than reaching in.

Treatment

The refactorings that cure it, and when to choose each.

Payoff

What you get once it's gone.

  • Rules about a piece of data live next to that data, so you find and change them in one place.
  • Internal fields can become private, since outsiders ask for results instead of raw values.
  • Duplicate calculations across services collapse into a single method.
  • The envious class gets smaller and its remaining code reflects its actual responsibility.

When to leave it

Sometimes it's not worth fixing.

  • Patterns like Strategy or Visitor deliberately keep behaviour apart from the data so you can swap or add operations without touching the data classes.
  • Mappers, serializers and view models exist to read another object's fields and translate them; that is their job, not envy.
  • The data class is generated code or comes from a third-party library you cannot change; a local helper or wrapper is the practical option.
  • Moving the method would drag a dependency (database, HTTP client, clock) into a pure domain object; keep the I/O outside and move only the pure calculation.

Common questions

Short answers to the usual doubts.

How do I decide where a method belongs when it uses data from two classes?

Count what it uses. Put it with the class whose data it touches most. If it splits evenly, extract the part that uses each class and move each piece to its owner, leaving a thin coordinating method that combines them.

Is Feature Envy the same as the Law of Demeter?

They are related but not identical. Demeter violations are about chaining through collaborators, such as a.b().c(). Feature Envy is about where the work happens. A method can envy a direct parameter without any chaining, and chains often show up as a symptom of envy.

Doesn't moving logic into entities conflict with keeping a thin domain and fat services?

That style tends to produce envious services by design. You can keep services for orchestration, transactions and I/O while pushing calculations that depend only on an object's own state into that object. The result is easier to test because the moved logic needs no mocks.

How would I explain Feature Envy in an interview?

Define it in one sentence: a method that uses another object's data more than its own. Then give a short concrete case, such as a planner computing reorder quantities from a stock item's fields, and say the fix is to extract and move that calculation onto the item. Mention one exception, like Strategy, to show you know when not to apply it.

Does a getter-heavy class always mean Feature Envy elsewhere?

Not always, but it is a strong hint. Search for callers that combine several of those getters in a calculation. If you find the same combination in more than one place, that is envy, and the calculation should become a method on the class.

Next guide2 of 5 · Smells: couplingInappropriate Intimacy: Classes That Know Too Much About Each OtherRead the next one