Feature Envy

November 24, 202611 minutes

A method that keeps reaching into another class's data wishes it lived somewhere else. Learn to spot Feature Envy and fix it with Move Method: put behavior next to the data it uses.

order.getCustomer().getAddress().getZip(). You’ve probably written a line like this, or at least approved one in a code review. It lives in a shipping service, yet almost everything it touches belongs to somebody else. When a method cares more about another class’s data than about its own, the code has a smell with a memorable name: Feature Envy.

Prefer to watch? The narrated video covers the same lesson (about 9 minutes). The article follows it section by section, with diagrams and a little extra depth.

Three hops from home

Here’s the line:

String zip = order.getCustomer().getAddress().getZip();

Follow the dots. We start at the order, hop to its customer, hop to the customer’s address, and finally pull out the zip code. That’s three hops away from where the code lives.

The code lives in ShippingService, but it walks from an Order to its Customer to the Customer's Address and finally reads the zip, three hops away from home. The code lives in ShippingService, but it walks from an Order to its Customer to the Customer's Address and finally reads the zip, three hops away from home.
The code lives in one class; the data lives three hops away.

Now ask a strange question: whose code is this? It’s like cooking dinner by walking into your neighbor’s kitchen, opening their fridge, and carrying the ingredients home one at a time. The cooking happens in one house; the ingredients live in another.

What it looks like

Here’s the whole shipping service. It has one field of its own, a base rate, and two methods:

class ShippingService {
    private final double baseRate = 4.99;

    boolean isRemote(Order order) {
        Address a = order.getCustomer().getAddress();
        return a.getCountry().equals("US")
            && a.getZip().startsWith("99");
    }

    double cost(Order order) {
        double weight = 0;
        for (Item item : order.getItems()) {
            weight += item.getWeight() * item.getQuantity();
        }
        double rate = isRemote(order) ? 2.0 : 0.5;
        return baseRate + weight * rate;
    }
}

Let’s count who each method talks to (one point per call or field use, grouped by the class that receives it):

MethodShippingService (own)OrderCustomerAddressItem
isRemote()01120
cost()2 (baseRate, isRemote)1002

isRemote() asks the order for its customer, the customer for an address, and the address for a country and a zip code. And how many times does it use its own class? Zero. Not one field, not one method. Every bit of data it needs lives somewhere else.

isRemote in ShippingService uses nothing of its own class. It calls getCustomer on Order, getAddress on Customer, and getCountry and getZip on Address. isRemote in ShippingService uses nothing of its own class. It calls getCustomer on Order, getAddress on Customer, and getCountry and getZip on Address.
isRemote() talks to three other classes and never to its own.

cost() is more mixed. It does use the base rate, and it calls isRemote(). But the loop in the middle asks each item for its weight and its quantity, and does math that only items care about.

That’s the smell. Feature Envy (named by Martin Fowler in Refactoring) is a method that is more interested in another class’s data than in its own. The method wishes it lived somewhere else.

Why it hurts

So what’s the harm? The code works. The trouble starts when the data changes.

Feature envy rarely comes alone. Elsewhere in the codebase, the invoice printer formats the zip code and the tax service reads its first two digits:

// ShippingService
boolean remote = a.getZip().startsWith("99");

// InvoicePrinter
String line3 = a.getZip() + " " + a.getCity();

// TaxService
String region = a.getZip().substring(0, 2);

Each one knows exactly how an address is shaped. Now the shop goes international. Outside the US there’s no zip code, just a postal code. One change inside Address, and every envious method breaks:

One change inside Address, renaming zip to postalCode for international shipping, breaks ShippingService, InvoicePrinter and TaxService, because each of them reads getZip directly. One change inside Address, renaming zip to postalCode for international shipping, breaks ShippingService, InvoicePrinter and TaxService, because each of them reads getZip directly.
One change to the data, edits in every envious class.
  • Coupling. Address can’t change its own insides without breaking classes that have nothing to do with addresses.
  • Copied rules. “Is this address remote?” or “what’s the region?” gets re-implemented wherever someone needs it.
  • Bugs. Sooner or later, one copy misses an update, and you ship a bug.

Repeat this across a codebase, and every small change turns into edits in many files. That has its own name, Shotgun Surgery, and it’s the subject of the next lesson.

How to spot it

Four quick tests you can run in a code review:

  1. Count the references. If a method uses another object’s getters more than its own fields, it’s envious. (isRemote(): four foreign getters, zero own fields.)
  2. Look for getter chains: get().get().get(). Every hop means the method knows more about the structure than it should.
  3. It uses nothing from its own class. Your IDE might even suggest making it static (IntelliJ: “Method can be static”). That’s a strong hint it lives in the wrong place.
  4. The same group of getters shows up in several places, like getZip() in three classes above. That’s one piece of logic, copied around, with no home.
Decision flowchart for a suspicious method. If it uses another object's data more than its own, ask whether it uses anything of its own class. If not, move the whole method. If it does, extract the envious part, then move it. If it mostly uses its own data, it is probably fine. Decision flowchart for a suspicious method. If it uses another object's data more than its own, ask whether it uses anything of its own class. If not, move the whole method. If it does, extract the envious part, then move it. If it mostly uses its own data, it is probably fine.
Is this method envious, and which fix applies?

Test two has a famous rule behind it: the Law of Demeter. A method should only talk to its friends: its own object, its parameters, its fields, and the objects it creates. Not the friends of its friends.

Law of Demeter. A method may call methods on this, its parameters, its fields and objects it creates. Calling methods on objects returned by its friends, the friends of friends, is not allowed. Law of Demeter. A method may call methods on this, its parameters, its fields and objects it creates. Calling methods on objects returned by its friends, the friends of friends, is not allowed.
Talk to your friends, not to the friends of your friends.

Demeter is sometimes summarized as “use only one dot”, but that’s a rule of thumb, not the law: fluent builders and stream pipelines (list.stream().filter(...).map(...)) chain dots without reaching into anyone’s structure. What matters is whose internals you’re navigating.

The key insight: tell, don’t ask

So what’s the fix? Back to the kitchen. Instead of raiding your neighbor’s fridge, you ask your neighbor to cook. The work happens where the ingredients are.

In code, that’s the core principle: put behavior next to the data it uses. Some people call it Tell, Don’t Ask: don’t ask an object for its data and decide for it; tell it what you need.

Ask: ShippingService asks Order for the customer, Customer for the address, and Address for the country and the zip, then decides itself whether the address is remote. Ask: ShippingService asks Order for the customer, Customer for the address, and Address for the country and the zip, then decides itself whether the address is remote.
Ask: fetch the data, decide outside.
Tell: ShippingService asks Address one question, isRemote, and Address answers true using its own fields. Tell: ShippingService asks Address one question, isRemote, and Address answers true using its own fields.
Tell: one question, answered where the data lives.

The refactoring is called Move Method. isRemote() only uses the address’s data, so we move it into the Address class:

class Address {
    private String zip;
    private String country;

    boolean isRemote() {
        return country.equals("US") && zip.startsWith("99");
    }
}

Inside the address, the getters disappear. It simply reads its own country and zip fields, and isRemote() no longer needs a parameter. Back in the shipping service, the call site shrinks. We get the address and simply ask: are you remote?

double cost(Order order) {
    double weight = 0;
    for (Item item : order.getItems()) {
        weight += item.getWeight() * item.getQuantity();
    }
    Address a = order.getCustomer().getAddress();
    double rate = a.isRemote() ? 2.0 : 0.5;
    return baseRate + weight * rate;
}

What “remote” means now lives in exactly one place. If the rule changes (Hawaii too? postal codes abroad?), you change Address and nothing else.

How to move a method safely, step by step:

  1. Copy the method into the target class and adapt it: parameters that pointed at the target become this, getters become fields.
  2. Turn the old method into a one-line delegate (return order.getCustomer().getAddress().isRemote();) and run the tests.
  3. Replace the callers and delete the delegate. IDEs automate all of this (IntelliJ: Refactor → Move Instance Method).

Put behavior next to the data it uses. Tell, don’t ask.

When only part envies: extract, then move

cost() is different. Only part of it is envious. It still needs the base rate, which belongs to the shipping service, so we can’t move the whole method.

The answer is two steps. Step one: Extract Method. Pull the envious loop out into its own method, totalWeight:

double cost(Order order) {
    Address a = order.getCustomer().getAddress();
    double rate = a.isRemote() ? 2.0 : 0.5;
    return baseRate + totalWeight(order) * rate;
}

double totalWeight(Order order) {
    double weight = 0;
    for (Item item : order.getItems()) {
        weight += item.getWeight() * item.getQuantity();
    }
    return weight;
}

Now look at totalWeight. It uses nothing but the order’s items. That’s pure envy, so step two is the same move as before: Move Method into Order, where it loops over its own items:

class Order {
    private List<Item> items;

    double totalWeight() {
        double weight = 0;
        for (Item item : items) {
            weight += item.getWeight() * item.getQuantity();
        }
        return weight;
    }
}

And cost() now reads cleanly: base rate, plus the order’s total weight, times the rate.

double cost(Order order) {
    Address a = order.getCustomer().getAddress();
    double rate = a.isRemote() ? 2.0 : 0.5;
    return baseRate + order.totalWeight() * rate;
}
Refactoring steps for cost: it is partly envious, so first Extract Method pulls the loop into totalWeight(order), then Move Method moves it into Order as totalWeight(), and cost calls order.totalWeight(). Refactoring steps for cost: it is partly envious, so first Extract Method pulls the loop into totalWeight(order), then Move Method moves it into Order as totalWeight(), and cost calls order.totalWeight().
Extract first, then move.

Here’s where everything lives after both moves:

Class diagram after the refactoring. ShippingService has baseRate and cost(order). Order has items and totalWeight() and holds a Customer and Items. Customer holds an Address. Address has zip, country and isRemote(). Item has weight and quantity. Class diagram after the refactoring. ShippingService has baseRate and cost(order). Order has items and totalWeight() and holds a Customer and Items. Customer holds an Address. Address has zip, country and isRemote(). Item has weight and quantity.
Each piece of behavior now sits next to its data.

Notice the loop still asks each item for two numbers. One more small move could give Item its own weight() method. Stop when the code reads well; refactoring is a direction, not a destination.

Extract first, then move. When only part of a method envies another class, cut out that part, and send it home.

A second example: the library late fee

The same smell, from a library system. A late fee calculator works out the fine for a book that comes back late:

class LateFeeCalculator {
    double fee(Loan loan, LocalDate today) {
        LocalDate due = loan.getDueDate();
        if (!today.isAfter(due)) {
            return 0;
        }
        long days = ChronoUnit.DAYS.between(due, today);
        double daily = loan.getBook().getCategory().getDailyFee();
        return Math.min(days * daily, loan.getBook().getPrice());
    }
}

Look at what it touches: the loan’s due date; the loan’s book, the book’s category, the category’s daily fee, and the book’s price. Loan three times, Book twice, Category once. Its own class contributes nothing.

So we move it. The fee becomes a method on the loan, lateFee, and it reads the loan’s own due date directly:

class Loan {
    private Book book;
    private LocalDate dueDate;

    double lateFee(LocalDate today) {
        if (!today.isAfter(dueDate)) {
            return 0;
        }
        long days = ChronoUnit.DAYS.between(dueDate, today);
        return Math.min(days * book.dailyFee(), book.getPrice());
    }
}

The chain through the book gets shorter too. The loan asks the book for its daily fee, and the book asks its own category:

class Book {
    private Category category;
    private double price;

    double dailyFee() { return category.getDailyFee(); }
    double getPrice() { return price; }
}
After the move, a caller asks the Loan for lateFee(today). The Loan asks its Book for dailyFee(), the Book asks its Category for getDailyFee(), and the Loan asks the Book for getPrice(). Each class only talks to its direct neighbor. After the move, a caller asks the Loan for lateFee(today). The Loan asks its Book for dailyFee(), the Book asks its Category for getDailyFee(), and the Loan asks the Book for getPrice(). Each class only talks to its direct neighbor.
Each class only talks to its neighbor.

The calculator has nothing left to do, so it disappears. Now any caller simply asks the loan for its late fee: loan.lateFee(today).

If late-fee rules later grow complicated (members pay less, holidays don’t count), that’s the moment to pull them back out into a deliberate policy object, which brings us to the exceptions below.

Commonly confused: Message Chains and Inappropriate Intimacy

Two other smells look a lot like feature envy, and people mix them up all the time.

Message Chains is the long trail of dots itself. Even after our fix, cost() still walks from the order, to the customer, to the address:

Address a = order.getCustomer().getAddress();

The cure there is Hide Delegate: give the order a method that hands over the shipping address, so callers don’t need to know the path:

class Order {
    private Customer customer;

    Address shippingAddress() {
        return customer.getAddress();
    }
}

double rate = order.shippingAddress().isRemote() ? 2.0 : 0.5;

Feature envy asks which class a method belongs in. Message chains ask how far a caller has to travel. You often fix them together, but they’re different problems.

Inappropriate Intimacy is the third one. Two classes keep reaching into each other’s private details, in both directions: Order pokes at Invoice’s tax lines while Invoice rewrites Order’s totals. Envy is one method with a crush on another class. Intimacy is two classes that are far too close. Typical fixes: Move Method and Move Field until one class owns each piece of data, make a two-way association one-way, or Extract Class for the shared part.

Three smells by symptom. A method that uses another class's data more than its own is Feature Envy, fixed by Move Method. A caller that walks a long path of getters is Message Chains, fixed by Hide Delegate. Two classes that reach into each other's internals in both directions are Inappropriate Intimacy, fixed by Move Method or Field or Extract Class. Three smells by symptom. A method that uses another class's data more than its own is Feature Envy, fixed by Move Method. A caller that walks a long path of getters is Message Chains, fixed by Hide Delegate. Two classes that reach into each other's internals in both directions are Inappropriate Intimacy, fixed by Move Method or Field or Extract Class.
Same family, different symptoms, different fixes.
Feature EnvyMessage ChainsInappropriate Intimacy
The questionWhich class does this method belong in?How far does the caller travel?Which class owns this data?
Directionone method → another classcaller → a path of objectstwo classes ↔ each other
Typical fixMove Method (+ Extract Method)Hide DelegateMove Method/Field, Extract Class

When it’s acceptable

So, should every envious method move? No. Sometimes keeping behavior apart from the data is exactly the point.

  • Strategy. The Strategy pattern puts pricing rules in separate objects so you can swap them at run time. Those strategies read the order’s data on purpose.
  • Visitor. The Visitor pattern does the same, keeping operations outside a class hierarchy so you can add operations without touching every class (the flip side of dynamic dispatch).
  • Mappers and serializers. A mapper that turns an order into a data transfer object reads every getter. That’s its whole job:
class OrderMapper {
    OrderDto toDto(Order order) {
        return new OrderDto(
            order.getId(),
            order.getCustomer().getName(),
            order.totalWeight());
    }
}

Also, think about direction. Moving formatting code (an HTML label, a PDF line) into your domain class would drag user interface concerns into it. Domain classes shouldn’t know about screens; the screen layer is allowed to read the domain. If the separation is deliberate, the envy is by design.

Should this envious method move? If keeping it apart is the point, as in Strategy, Visitor or a mapper, keep it where it is. If moving it would drag UI or infrastructure into the domain, keep it too. Otherwise, move it next to its data. Should this envious method move? If keeping it apart is the point, as in Strategy, Visitor or a mapper, keep it where it is. If moving it would drag UI or infrastructure into the domain, keep it too. Otherwise, move it next to its data.
If the separation is deliberate, the envy is by design.

Recap

Feature envy is a method more interested in another class’s data than its own. Spot it by counting references, following getter chains, and noticing methods that ignore their own class. Fix it with Move Method; when only part of a method envies, Extract Method first, then move. Tell, don’t ask.

Recap chain: spot it by counting references, getter chains and methods that ignore their own class; fix it with Move Method, extracting first if only part envies; the result is behavior that lives with its data. Recap chain: spot it by counting references, getter chains and methods that ignore their own class; fix it with Move Method, extracting first if only part envies; the result is behavior that lives with its data.
Spot it, move it, and let behavior live with its data.
  • Feature Envy: a method that uses another class’s data more than its own.
  • It hurts because it couples classes to each other’s internals and copies rules around; repeated, it becomes Shotgun Surgery.
  • Spot it: foreign getters outnumber own fields, getter chains (Law of Demeter), “could be static”, the same getters in several places.
  • Fix it: Move Method; Extract Method first if only part envies; Hide Delegate for the chain that remains.
  • Leave it when the separation is the point (Strategy, Visitor, mappers) or moving would break your layering.

Don’t raid the neighbor’s fridge. Put behavior next to the data it uses.

Further reading