Coding Practice: Feature Envy

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

About Chris VanHoose

Principal Software Architect at CT Lien Solutions
This entry was posted in Software Architecture and tagged , , . Bookmark the permalink.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.