Skip to main content
Clean Code 50 XP · 5 min

Feature Envy

A method that spends most of its time reading another class's data belongs in that class.

Showing
Ad (728×90)

Recognising Feature Envy

G14: Feature Envy is a code smell where a method in one class is obsessed with the data of another class. Instead of working with its own data, it makes repeated calls to getters — or directly reads fields — of a foreign object. The tell-tale sign: the method's parameter list or body references one external object far more than its own class.

The Refactoring: Move the Method

The cure is almost always the same: move the method to the class it envies. If Billing.calculateBill reads only Customer data, it belongs in Customer. The enclosing class becomes a thin coordinator — it calls the method on the object that owns the logic. This improves cohesion, reduces coupling, and makes the code easier to test in isolation.

Code Challenge

Move the billing calculation method to the Customer class.

Key takeaway

A method belongs where its data lives. If it envies another class, move it there.

Done with this lesson?

Mark it complete to earn XP and track your progress.