Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I correct feature envy in this case?

I have some code that looks like:

class Parent {
 private Intermediate intermediateContainer;
 public Intermediate getIntermediate();
}

class Intermediate {
 private Child child;
 public Child getChild() {...}
 public void intermediateOp();
}

class Child {
 public void something();
 public void somethingElse();
}

class Client {
 private Parent parent;

 public void something() {
  parent.getIntermediate().getChild().something();
 }

 public void somethingElse() {
  parent.getIntermediate().getChild().somethingElse();
 }

 public void intermediate() {
  parent.getIntermediate().intermediateOp();
 }
}

I understand that is an example of the "feature envy" code smell. The question is, what's the best way to fix it? My first instinct is to put the three methods on parent:

parent.something();
parent.somethingElse();
parent.intermediateOp();

...but I feel like this duplicates code, and clutters the API of the Parent class (which is already rather busy).

Do I want to store the result of getIntermediate(), and/or getChild(), and keep my own references to these objects?

like image 322
RMorrisey Avatar asked May 25 '10 23:05

RMorrisey


1 Answers

This isn't exactly Feature Envy, but more of a high coupling issue between these classes and a definite violation of the Law of Demeter http://www.ccs.neu.edu/research/demeter/demeter-method/LawOfDemeter/general-formulation.html. Your first thought of having the methods directly on the parent is a good though. Clients should not need to call through the stack like that.

If you're concerned about the parent being too busy, maybe you have too much functionality in there and it should be split into some smaller classes. Classes should be single purposed.

like image 98
Jeff Storey Avatar answered Sep 21 '22 17:09

Jeff Storey