How do I fix envy in this case?

I have a code that looks like this:

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 this is an example of the envy code smell. The question is, what is the best way to fix it? My first instinct is to put three methods in the parent:

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

... but I feel this duplicates the code and clutters up the Parent class API (which is already pretty busy).

I want to save the result of getIntermediate () and / or getChild () and save my own references to these objects?

+5
source share
3 answers

, , ( " " ), API, . , , , API, .

"" , - , ( ) - . , , , , . , .

, , , "", - . , !

+5

Client? parent , , , ?

parent , - parent Client.

+3
source

All Articles