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.
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.
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.
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):
| Method | ShippingService (own) | Order | Customer | Address | Item |
|---|---|---|---|---|---|
isRemote() | 0 | 1 | 1 | 2 | 0 |
cost() | 2 (baseRate, isRemote) | 1 | 0 | 0 | 2 |
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.
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.
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:
Address can’t change its own insides without breaking classes that have
nothing to do with addresses.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.
Four quick tests you can run in a code review:
isRemote(): four foreign getters, zero own fields.)get().get().get(). Every hop means the method knows more about
the structure than it should.static
(IntelliJ: “Method can be static”). That’s a strong hint it lives in the wrong place.getZip() in three classes
above. That’s one piece of logic, copied around, with no home.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.
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.
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.
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:
this, getters become fields.return order.getCustomer().getAddress().isRemote();)
and run the tests.Put behavior next to the data it uses. Tell, don’t ask.
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;
}Here’s where everything lives after both moves:
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.
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; }
}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.
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.
| Feature Envy | Message Chains | Inappropriate Intimacy | |
|---|---|---|---|
| The question | Which class does this method belong in? | How far does the caller travel? | Which class owns this data? |
| Direction | one method → another class | caller → a path of objects | two classes ↔ each other |
| Typical fix | Move Method (+ Extract Method) | Hide Delegate | Move Method/Field, Extract Class |
So, should every envious method move? No. Sometimes keeping behavior apart from the data is exactly the point.
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.
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.
Don’t raid the neighbor’s fridge. Put behavior next to the data it uses.