August 6, 2017

...Learn TDD with Codemanship

What *Exactly* Is "Feature Envy"?

I'm currently writing some custom FxCop rules for the trial Codemanship Code Craft "driving test" on Sept 16th. The aim is that not only will I be able to automatically check candidate's code, but they will be able to while they're writing it, too. The power of Continuous Inspection!

One of the rules is that methods of one class must not display Feature Envy for another class. Typically, Feature Envy's defined as:

A method accesses the features of another class more than its own.


And this might seem trivial to check for using a tool like FxCop. Look at all the member bindings inside a method. If there are more bindings to members of other types then to members of the type on which this method's declared, then we've got Feature Envy. To fix it, we can just move the method to the focus of its envy.

But I'm not sure it's quite that simple. This example might be an open-and-shut case:



But how about this?



The majority of feature calls in this method are to methods of the same class. But that code smell we saw in the first example is still here, on lines 3 and 4. Proof? What if we extract those 2 lines into their own method?



The method obviousFeatureEnvy now completely satisfies our definition of Feature Envy and should be moved to the other class.

I think this leads me to a better definition of Feature Envy:

Feature Envy is when any unit of executable code - a method, a block, a statement or an expression - uses features of another class more than features of its own class


Basically, if you can extract any portion of code into a method that displays the original, "classic" definition of Feature Envy.

But wait; there's more. Take a look at this example:



Technically, only one of these methods satisfies our definition of Feature Envy, but if were to inline the call stack, we'd end up with one method with very obvious Feature Envy.

It's much more complex than I thought. But, for the driving test, I'll probably keep it simple and stick with the classic - and much easier - definition of Feature Envy.

But one day, when I've got time...




Posted 4 months, 1 day ago on August 6, 2017