# Feature EnvyA 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.

{{< lesson-video youtube="G_mq1oN4F5w" title="Feature Envy" >}}

## Three hops from home

Here's the line:

```java
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.

```mermaid {alt="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." caption="The code lives in one class; the data lives three hops away."}
flowchart TD
  S["ShippingService<br/>(the code lives here)"] --> O["order"]
  O -->|"getCustomer()"| C["customer"]
  C -->|"getAddress()"| A["address"]
  A -->|"getZip()"| Z["zip"]
  class S c6
  class O c4
  class C c5
  class A c1
  class Z hl
```

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:

```java
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.

```mermaid {alt="isRemote in ShippingService uses nothing of its own class. It calls getCustomer on Order, getAddress on Customer, and getCountry and getZip on Address." caption="isRemote() talks to three other classes and never to its own."}
flowchart LR
  M["ShippingService.isRemote()"] -->|"getCustomer()"| O["Order"]
  M -->|"getAddress()"| C["Customer"]
  M -->|"getCountry()<br/>getZip()"| A["Address"]
  M -.->|"0 uses"| OWN["its own fields"]
  class M c6
  class O c4
  class C c5
  class A c1
  class OWN bad
```

`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:

```java
// 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:

```mermaid {alt="One change inside Address, renaming zip to postalCode for international shipping, breaks ShippingService, InvoicePrinter and TaxService, because each of them reads getZip directly." caption="One change to the data, edits in every envious class."}
flowchart LR
  R["Address: zip becomes<br/>postalCode"] --> S["ShippingService<br/>getZip() breaks"]
  R --> I["InvoicePrinter<br/>getZip() breaks"]
  R --> T["TaxService<br/>getZip() breaks"]
  class R warn
  class S,I,T bad
```

- **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](/code-smells/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.

```mermaid {alt="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." caption="Is this method envious, and which fix applies?"}
flowchart TD
  Q1{"Uses another object's data<br/>more than its own?"} -->|no| F["Probably fine"]
  Q1 -->|yes| Q2{"Uses any field or method<br/>of its own class?"}
  Q2 -->|no| MM["Move Method<br/>(the whole method)"]
  Q2 -->|yes| EM["Extract Method,<br/>then Move Method"]
  class F good
  class MM,EM hl
  class Q1,Q2 warn
```

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.

```mermaid {alt="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." caption="Talk to your friends, not to the friends of your friends."}
flowchart TD
  M["a method"] --> T["this"]
  M --> P["parameters"]
  M --> F["fields"]
  M --> N["new objects"]
  P -.-> X1["friend of a friend<br/>order.getCustomer()..."]
  F -.-> X2["friend of a friend"]
  class M hl
  class T,P,F,N good
  class X1,X2 bad
```

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.

```mermaid {alt="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." caption="Ask: fetch the data, decide outside."}
sequenceDiagram
  participant S as ShippingService
  participant O as Order
  participant C as Customer
  participant A as Address
  S->>O: getCustomer()
  O-->>S: customer
  S->>C: getAddress()
  C-->>S: address
  S->>A: getCountry()
  A-->>S: "US"
  S->>A: getZip()
  A-->>S: "99501"
  Note over S: decides "remote" itself
```

```mermaid {alt="Tell: ShippingService asks Address one question, isRemote, and Address answers true using its own fields." caption="Tell: one question, answered where the data lives."}
sequenceDiagram
  participant S as ShippingService
  participant A as Address
  S->>A: isRemote()
  Note over A: reads its own country and zip
  A-->>S: true
```

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

```java
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?*

```java
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`:

```java
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:

```java
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.

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

```mermaid {alt="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()." caption="Extract first, then move."}
flowchart LR
  A["cost()<br/>partly envious"] --> B["Extract Method<br/>totalWeight(order)"]
  B --> C["Move Method<br/>Order.totalWeight()"]
  C --> D["cost() calls<br/>order.totalWeight()"]
  class A warn
  class B,C hl
  class D good
```

Here's where everything lives after both moves:

```mermaid {alt="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." caption="Each piece of behavior now sits next to its data."}
classDiagram
  class ShippingService {
    -double baseRate
    +cost(Order order) double
  }
  class Order {
    -List~Item~ items
    +totalWeight() double
  }
  class Customer {
    +getAddress() Address
  }
  class Address {
    -String zip
    -String country
    +isRemote() boolean
  }
  class Item {
    +getWeight() double
    +getQuantity() int
  }
  ShippingService ..> Order : uses
  Order o--> Customer
  Order o--> "*" Item
  Customer o--> Address
```

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:

```java
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:

```java
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:

```java
class Book {
    private Category category;
    private double price;

    double dailyFee() { return category.getDailyFee(); }
    double getPrice() { return price; }
}
```

```mermaid {alt="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." caption="Each class only talks to its neighbor."}
sequenceDiagram
  participant Caller
  participant L as Loan
  participant B as Book
  participant C as Category
  Caller->>L: lateFee(today)
  L->>B: dailyFee()
  B->>C: getDailyFee()
  C-->>B: 0.25
  B-->>L: 0.25
  L->>B: getPrice()
  B-->>L: 18.00
  L-->>Caller: fee
```

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](/code-smells/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:

```java
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:

```java
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](/code-smells/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.

```mermaid {alt="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." caption="Same family, different symptoms, different fixes."}
flowchart LR
  S1["one method uses another<br/>class's data more than its own"] --> E["Feature Envy"] --> F1["Move Method<br/>(Extract first if partial)"]
  S2["a caller walks a long<br/>path of getters"] --> M["Message Chains"] --> F2["Hide Delegate"]
  S3["two classes reach into each<br/>other's internals, both ways"] --> I["Inappropriate Intimacy"] --> F3["Move Method / Field,<br/>Extract Class"]
  class E bad
  class M c4
  class I c5
  class F1,F2,F3 good
```

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

## When it's acceptable

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

- **[Strategy](/patterns/strategy-pattern/).** 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](/patterns/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](/fundamentals/dynamic-dispatch/)).
- **Mappers and serializers.** A mapper that turns an order into a data transfer object reads
  every getter. That's its whole job:

```java
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.

```mermaid {alt="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." caption="If the separation is deliberate, the envy is by design."}
flowchart TD
  Q1{"Is keeping it apart the point?<br/>Strategy, Visitor, mapper"} -->|yes| K1["Keep it: envy by design"]
  Q1 -->|no| Q2{"Would moving it drag UI or<br/>infrastructure into the domain?"}
  Q2 -->|yes| K2["Keep it in its layer"]
  Q2 -->|no| MV["Move it next to its data"]
  class K1,K2 good
  class MV hl
  class Q1,Q2 warn
```

## 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.

```mermaid {alt="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." caption="Spot it, move it, and let behavior live with its data."}
flowchart LR
  A["Spot it<br/>counts, chains,<br/>ignores own class"] --> B["Fix it<br/>Move Method<br/>(Extract first)"]
  B --> C["Behavior lives<br/>with its data"]
  class A bad
  class B hl
  class C good
```

- **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](/code-smells/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

- Martin Fowler, *Refactoring: Improving the Design of Existing Code* (2nd ed.), chapter 3
  ("Bad Smells in Code") and the Move Function / Extract Function refactorings.
- [Refactoring.Guru: Feature Envy](https://refactoring.guru/smells/feature-envy)
- Martin Fowler, [TellDontAsk](https://martinfowler.com/bliki/TellDontAsk.html)
- Related lessons: [Shotgun Surgery](/code-smells/shotgun-surgery/),
  [Strategy Pattern](/patterns/strategy-pattern/),
  [State Pattern](/patterns/state-pattern/).
