1

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);
    }
}                    
Héctor
  • 24,444
  • 35
  • 132
  • 243
  • *For many modern object oriented languages that use a dot as field identifier, the law can be stated simply as "use only one dot". That is, the code a.b.Method() breaks the law where a.Method() does not.* per [Wiki](https://en.wikipedia.org/wiki/Law_of_Demeter) – Compass Oct 19 '17 at 15:36
  • 1
    Not at all. You are just calling a method of class D, not "diving" in its internal state. – Héctor Oct 19 '17 at 15:37
  • @Héctor Can you give me an example where the law is not respected ? – JaJaJaJapan Oct 19 '17 at 15:41
  • `object.getChild().sumOfNumbers(2,3);` – Compass Oct 19 '17 at 15:42
  • 1
    Typical code violating that law: `object.getUsers().add(new User());` instead of `object.addUser(new User())` – Héctor Oct 19 '17 at 15:43
  • Think about it this way: Whenever you use getters (methods that return instance variables) it is very likely that you will have violations of the Law of Demeter. If you don't use getters then it is very unlikely. So basically just don't write or use getters and you'll be fine. – Robert Bräutigam Oct 23 '17 at 08:04

1 Answers1

2

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);
    }
}
gil.fernandes
  • 12,978
  • 5
  • 63
  • 76
  • if we have C myC = new C(); int x = myC.sumOfNumbers(2,3); that wouldn't be considered a violation. right? – JaJaJaJapan Oct 19 '17 at 16:09
  • No, that is not a violation. You just perform a method call on a single object and get the result which is only an integer. – gil.fernandes Oct 19 '17 at 16:11
  • ok it's not a violation also because the object myC was created inside the method f and the method sumOfNumbers() is being called inside of f – JaJaJaJapan Oct 19 '17 at 16:15