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!
Jdeodorant is an eclipse plugin, which promises finding feature envy and visualizing it. I wanted to use it for a simple example, but the plugin didn’t work properly.
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 😀
4 thoughts on “Code Smell: Feature Envy”
Pingback: Beyond coding – Levels of Errors in Software Development – Part 1 | Waog
I’m creating some internal training to use at our company and I’d love to reference your posts on code smells but I do not see anything about copyrights on the images. Would it be okay if I used some of the images in our training if we also include the links to your blog entries?
LikeLiked by 1 person
I’m happy you like my posts.
Feel free to use them for your training, as long as you reference them. 🙂
If you like to tell me, I’d be interested in which company this training is held and how it was going.
Hey!! Can you expliened all the Code Smells Please!