Search code examples
javacoding-stylegettercomposition

Is it best to call a method (from class A) in a class (class B) which then calls a method in a class (C) or to use a getter for Class C in Class B?


E.g.

In Class A:

b.doThing();

In Class B:

doThing() {
    c.doThing();
}

OR

In class A:

b.getClassC().doThing();

What is the convention for a situation like this?


Solution

  • According to the Law of Demeter, you should go the first way, i.e. only call the method of class B which itself delegates to class C. This way, you reduce dependencies between your classes which is basically a good thing for reusability and maintainability.