Feature Envy

Keywords: feature envy, code ai

Feature Envy is a code smell where a method in Class A is more interested in the data and capabilities of Class B than in its own class — repeatedly accessing fields, getters, or methods of another object rather than using its own class's data — indicating that the method belongs in the class it is envying, not the class it currently lives in, and should be moved to restore proper encapsulation and cohesion.

What Is Feature Envy?

The smell manifests when a method's body is dominated by calls to external objects:

``python
# Feature Envy: OrderPricer is envious of Customer and Product
class OrderPricer:
def calculate_discount(self, order):
customer_type = order.customer.get_type() # Customer data
customer_years = order.customer.get_tenure() # Customer data
product_category = order.product.category # Product data
product_base_price = order.product.price # Product data
# 90% of this method's logic uses Customer and Product,
# not OrderPricer's own data
if customer_type == "premium" and customer_years > 2:
return product_base_price * 0.85
elif product_category == "sale":
return product_base_price * 0.90
return product_base_price

# Better: Move to Customer or create a discounting domain object
class Customer:
def calculate_discount_for(self, product):
if self.type == "premium" and self.tenure_years > 2:
return product.price * 0.85
elif product.category == "sale":
return product.price * 0.90
return product.price
`

Why Feature Envy Matters

- Encapsulation Violation: Feature Envy is a direct indication of broken encapsulation. Object-oriented design requires that behavior (methods) lives with the data it operates on. When a method in Class A primarily reads and manipulates data from Class B, the method is in the wrong class — the invariants, validations, and semantic context for that data live in B, not A.
- Coupling Increase: Every time Class A's method accesses Class B's data, it creates a coupling dependency. If Class B's data structure changes (a field is renamed, split, or removed), Class A's method must be updated even though it's in a different class. Feature Envy spreads change radius unnecessarily.
- Cohesion Degradation: Class A, by hosting methods that primarily operate on unrelated data, has lower cohesion — its methods are no longer all working toward the same class purpose. This dilutes the single responsibility of both Class A (which now has foreign concerns mixed in) and Class B (which lacks the methods that its data deserves).
- Duplication Risk: When multiple classes are envious of the same external class, the envy logic is likely duplicated. Three different classes each implementing their own version of discount calculation based on Customer attributes — duplicating business logic that should live once in Customer.
- Testing Complexity: Testing an envious method requires constructing mock objects for the envied class. Moving the method into the envied class eliminates this mocking requirement — the method can be tested with the class's own state.

Detection

Feature Envy is detected by analyzing method body call patterns:

- Count external method calls per target class in a method body.
- If calls to Class B exceed calls to
self` methods/fields by a significant margin, the method is envious of B.
- The MMAC (Method-Method Access Correlation) metric formalizes this: methods with low self-data access correlation are Feature Envy candidates.
- The LAA (Locality of Attribute Accesses) metric measures what fraction of a method's attribute accesses are to its own class — low LAA indicates Feature Envy.

Exceptions

Not all external access is Feature Envy:
- Strategy Pattern: A strategy object that accepts data objects as parameters is designed to operate on external data — this is intentional and does not indicate envy.
- Builder/Factory: Construction methods that compile data from multiple sources and produce an assembled object.
- Event Handlers: Handlers that access the event source's data are doing exactly what they're designed to do.

Tools

- JDeodorant (Eclipse/Java): Automated Feature Envy detection with one-click Move Method refactoring suggestions.
- SonarQube: Feature Envy detection using LAA and ATFD (Access To Foreign Data) metrics.
- IntelliJ IDEA Inspections: "Method can be moved to" hints identify Feature Envy candidates.
- Designite: Design and implementation smell detection including Feature Envy for Java and C#.

Feature Envy is logic that is lost — a method that has wandered into the wrong class, far from the data it needs and the invariants it should be enforcing, creating unnecessary coupling between classes and diluting the cohesion that makes classes comprehensible, testable, and independently evolvable.

Want to learn more?

Search 13,225+ semiconductor and AI topics or chat with our AI assistant.

Search Topics Chat with CFSGPT