What is Feature Envy?

8

What is Feature Envy?

Why is it considered a bad smell of code ?

What are the advantages of avoiding it?

Should it ever be avoided?

    
asked by anonymous 12.03.2017 / 15:10

2 answers

7

One method can access data of another type to do some operation. When this becomes common it means that the object itself should perform this operation and deliver the result. Then it is said that a method was envious of a type and wanted to do it on its own.

You can not always avoid it because it depends on changing the original type you do not have access to or you can not change it for some reason. There are cases where behavior needs to be purposely separated.

The idea is that this violates the encapsulation and not so object oriented. As not everything needs this, even when it can is not something that always needs to be avoided. So much so that this is one of the cases that you have to choose which poison to take, because filling up one kind of methods to try to solve everything that may appear or leave the type open for change may be a bigger problem yet. It is common to have another smell which says that the correction is to do exactly what it says it can not.

There are types that exist only to provide data. This causes shivers in a lot of people, but used in the right thing is a good solution. So it's best to have utility classes or some famous design patterns that do composition to perform certain tasks that should not be treated by type.

It depends a lot on whether it has an advantage, in some cases the advantage is at least questionable.

I have the opinion that this is one of the classic examples of someone setting something by looking at detail and forgetting the whole. It's one of the things created by theorists.

    
12.03.2017 / 15:35
3

Feature Envy is when a method accesses the data of another object more than its own data. As a basic rule, if things change at the same time, you should keep them in the same place. Usually the data and functions that use this data are changed together (although exceptions are possible). If a method should clearly be moved to another location, use Move Method. If only part of a method accesses the data of another object, use the Extract method to move the part in question. If a method uses functions from several other classes, first determine which class contains most of the data used. Then place the method in this class along with the other data. Alternatively, use the Extract method to split the method into multiple parts that can be placed in different places in different classes.

When you ignore

Sometimes, the behavior is purposely kept separate from the class containing the data. The usual advantage of this is the ability to dynamically change behavior (see Strategy, Visitor, and other patterns).

    
12.03.2017 / 15:34