How do I correct feature envy in this case?

Posted by RMorrisey on Stack Overflow See other posts from Stack Overflow or by RMorrisey
Published on 2010-05-25T23:52:58Z Indexed on 2010/05/26 0:01 UTC
Read the original article Hit count: 229

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?

© Stack Overflow or respective owner

Related posts about java

Related posts about best-practices