Feature Envy


Symptoms

  • A method seems to be focused on manipulating the data of other classes rather than its own. (You may notice this because of duplication ”several clients do the same manipulation, or you may see the same object touched several times in a row.)

Causes

This is very common among clients of current and former data classes, but you can see it for any class and its clients.

What to Do

  • Move Method to put the actions on the correct class. (You may have to Extract Method first to isolate the misplaced part.)

Payoff

Reduces duplication. Often improves communication (since code moves to where people would expect it to be). May expose further refactoring opportunities.

Contraindications

Sometimes behavior is intentionally put on the "wrong" class. For example, some design patterns, such as Strategy or Visitor, pull behavior to a separate class so it can be independently changed. If you Move Method to put it back, you can end up putting things together that should change separately.

Notes

It's not always easy to distinguish Feature Envy from Inappropriate Intimacy (later in this chapter). Joshua Kerievsky of Industrial Logic suggests, "Feature Envy is when a class does so little on its own that it needs to ask lots of other classes things in order to do anything on its own. Inappropriate Intimacy is when a class reaches deep inside another class to get access to stuff it shouldn't have access to."

Exercise 34 Feature Envy.

Look back at Exercise 4 (Chapter 3). In Report.report() , notice how the information being printed is obtained by looking inside a Machine or Robot's fields. Fix these two examples of Feature Envy.

See Appendix A for solutions.




Refactoring Workbook
Refactoring Workbook
ISBN: 0321109295
EAN: 2147483647
Year: 2003
Pages: 146

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net