Methods suffer from Feature Envy, if they use other classes more than their own. This article describes why this is bad design, how to visualize feature envy and how to cure it.
Yesterday I wrote about a Code Smell called Data Class. There where classes holding only data, and methods in other classes which used that data. Today we take a look at the Code Smell these methods suffered from: Feature Envy.
What is Feature Envy?
Feature Envy is a Code Smell which occurs in methods. A method has Feature Envy on another class, if it uses more features (i.e. fields and methods) of another class than of its own.
Martin Fowler, the inventor of Code Smells and Feature Envy, puts it like this:
The whole point of objects is that they are a technique to package data with the processes used on that data. A classic smell is a method that seems more interested in a class other than the one it is in. The most common focus of the envy is the data.
Visualising Feature Envy
In Advantages of Graphical Notations #1 I emphasized how important graphical notations are to keep an overview over your code.
I haven’t found a common diagram type yet, to display the dependencies between different features. If you know one, please tell me!
So I came up with my own diagram type to display feature envy: the Feature Envy Diagram.
For the method in questions, there is one arrow pointing to each referred feature. Thick arrows mean many uses of the feature, thin arrow stand for less uses. Arrows pointing to the source class are green, while arrows to other classes have one color for each class (red in the example). If the total thickness of one colors arrows, exceeds the total thickness of the green arrows, we have feature envy.
How to handle it?
Give the method what it desires – the other class! Similar to the refactoring for Data Classes, you have to move the methods to its preferred class. For the example above, you have to move envyMethod() to ClassB. The result looks as follows:
Again, we reduced the coupling (red arrows) between our classes and raised the cohesion (green arrows) inside our classes. Have fun with your great new classes 😀