Feature Envy

A method uses another class’s data more than its own.

“A method commonly uses data/accessor methods of another class more than its own.” – Fowler & Beck

Signs of Use (Symptoms)

  • Method calls other.getX(), other.getY(), other.getZ() repeatedly.
  • The method would make more sense inside the other class.

Why it is bad (Consequences)

  • Misplaced Logic: Logic is in the wrong place.
  • Coupling: Tight coupling to the other class’s structure.

Why it happens (Root Cause)

Developer added logic where they were working, not where it belonged.

When it might be okay (Exceptions)

  • Strategy pattern (Strategy uses Host data).

Explanation

Problem

OrderPrinter accesses order.getLines(), order.getDiscount(), order.getTotal() all the time.

The Flaw

OrderPrinter “envies” the Order class. The logic belongs IN Order.

Real world analogy

A neighbor who keeps borrowing your tools. Maybe they should just own their own set.

Refactoring Solution

  • Move Method: Move the method to the class it envies.

Pros and Cons (of the Antipattern)

Pros (Why people do it) Cons (The price you pay)
  • Easier to add code where you are
  • High coupling
  • Logic in wrong place
  • Comparison

    • Related Antipatterns: Inappropriate Intimacy.
    • Related Principles: High Cohesion.

    Code example

    Typescript

    Bad (The Antipattern)

    Good (The Fix)