Search code examples
javalaw-of-demeter

Demeter Law - Calling a method of a class inside another method of a different class


If I have a class C containing a method f that takes as argument an object of type D (another class I defined)

If I call the methods of the object D inside of the method f, will I be violating the law of Demeter? and why?

Ex:

public C {
    public void f(D object) {
        int x = object.sumOfNumbers(2,3);
    }
}                    

Solution

  • This call does not violate Demeter's law. To violate it you will need to do this:

    In this case, an object A can request a service (call a method) of an object instance B, but object A should not "reach through" object B to access yet another object, C, to request its services

    Source: Wikipedia

    You are not reaching object C in your code.

    Using the class names (A, B, C) used in Wikipedia, your question code should look like this:

    public class A {
        public void f(B object) {
            int x = object.sumOfNumbers(2,3);
        }
    }
    

    There is here no C class you are accessing.

    And here is a violation of this law:

    public class A {
        public void f(B object) {
            C myC = object.getC();
            int x = myC.sumOfNumbers(2,3);
        }
    }