Course contentsShow
← Computer Science
Lesson 2333 of 2,87252. Clean Code and RefactoringFree lesson

Feature Envy Smell

Identify methods that spend more time working with data from other classes than their own class.

Feature Envy Smell

What you'll learn: You'll learn to spot when a method is overly interested in another class's data, signaling poor responsibility distribution.

What is Feature Envy?

Feature Envy occurs when a method spends more time accessing and manipulating data from another class than from its own. It's like a houseguest who keeps rummaging through your kitchen drawers instead of staying in the guest room—they're clearly in the wrong place.

This smell suggests the method is envious of the other class's features and probably belongs there instead.

Recognizing the Smell

Look for methods that:

  • Make multiple calls to getter methods of another object
  • Perform calculations using mostly external data
  • Seem more interested in another class's internals than their own
class Order:
    def __init__(self, customer):
        self.customer = customer
    
    def calculate_discount(self):
        # This method envies Customer's features!
        if self.customer.get_loyalty_points() > 1000:
            return self.customer.get_total_purchases() * 0.15
        elif self.customer.get_loyalty_points() > 500:
            return self.customer.get_total_purchases() * 0.10
        return 0

The calculate_discount method uses customer data far more than Order data. This logic likely belongs in the Customer class.

Why It Matters

Feature Envy breaks encapsulation and creates tight coupling. Changes to the Customer class ripple through Order, making both classes harder to maintain.

The fix? Apply Extract Method to move the envious behavior to where it belongs—the class it's obsessed with.

Key Takeaway: Feature Envy reveals misplaced responsibilities; when a method cares more about another class's data, it's a sign the method should move to that class.