Coding Practice: What is feature envy?
A method in Class A seems way too interested in the workings and data fields of Class B. The feature envy from Class A to Class B is an indication of tight coupling from Class A to Class B.
For example:
public class Tree { private IWaterService _waterService; public void DoSomething() { _waterService.CheckQuality(); if( _waterService.IsGoodQuality ) { _waterService.GetWaterSample(); _waterService.CheckWaterSample(); if( _waterService.IsSampleCollectedProperly ) { // ... } } } }
Quote:
“Not all cases are cut-and-dried. Often a method uses features of several classes, so which one should it live with? The heuristic we use is to determine which class has most of the data and put the method with that data.”
– Kent Beck
Application:
The usual fix for feature envy is to try moving the functionality of the interested method in ClassA to ClassB, which is already closer to most of the data involved in the task. In the above example, the logic in the DoSomething method probably belongs in the WaterService class itself.
References:
http://msdn.microsoft.com/en-us/magazine/cc947917.aspx – Cohesion and Coupling
http://dotnetslackers.com/Community/forums/tightly-coupled-and-loosely-coupled-objects/t/1835.aspx