Home Knowledge Base Feature Envy

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:

# 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

Detection

Feature Envy is detected by analyzing method body call patterns:

Exceptions

Not all external access is Feature Envy:

Tools

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.

feature envycode ai

Explore 500+ Semiconductor & AI Topics

From EUV lithography to CUDA optimization — search the full knowledge base or chat with our AI assistant.