Search code examples
javac#oopmethodscall

Calling a function 2 or more degrees below


I'm sure this is a classic case in OOP and the answer will be straightforward for most programmers, but I don't seem to find the explanation anywhere. Suppose I have a method belonging to a class A instantiated in a class B, like in the following code :

class A
{
    public void foo() {/*do something*/}
}       

class B
{
    public A objectA;

    public B()
    {
        objectA = new A();
    }

    public void call()
    {
        objectA.foo();
    }
}

Suppose now that I have a third class C that instantiates class B (which in turn instantiates class A with the code above) :

class C
{
    public C()
   {
       objectB = new B();
   }
}

What is the best way to call function foo() from class C (if any):

objectB.call();

or else

objectB.objectA.foo();

I feel that the first option might be the right answer in terms of modularity, but it seems redundant if the class B never has to call foo(). Is there a good answer here or is this whole pattern inherently flawed ? And if it is, what design principle does it violate and what are the workarounds?


Solution

  • According to the Law of Demeter: "Each unit should only talk to its friends; don't talk to strangers", or in another formulation, "Only talk to your immediate friends". Thus, the second option above is in strict violation of this principle.

    That being said, I guess having the need to fill multiple accessors methods in intermediate classes for the sole purpose of seeing the distant class is not a sign of great design.