2

Do helper utilities like the one below violate the spirit of the Law of Demeter? It doesn't technically violate the law, since the doOperate method doesn't invoke C's methods itself. If so is there a way to work around this so that the container class doesn't need getters and potentially setters for every field in every object contained within.

private static final class C{
    private String e;

    public C(String e) {
        this.e=e;
    }
    public String getE() {
        return e;
    }
}

private static final class D{
    private C c;

    public C getC() {
        return c;
    }

    public void setC(C c) {
        this.c=c;
    }
}

public static void doOperation(D d) {
    C c = d.getC();
    String e =getE(c);
    System.out.println(e);
}

private static String getE(C c){
   return c.getE();
}
  • 1
    getE(c)? Did you mean c.getE()? – candied_orange Apr 7 at 4:52
  • How is this an improvement over simply putting getE() inside your D class? – user949300 Apr 7 at 5:20
  • @candied_orange I updated the example with the missing getE method. – user3624390 Apr 7 at 14:41
0

I would say yes. Theoretically, it violates LoD if all these static methods belongs to the same component, because the component would know of C and its details (E being String).

If D, C or E ever change, the utility component will have to change too. Say E gets a different type or C is no longer accessible.

LoD advocates for tell, don't ask rule. So, if you want print E, the LoD-friendly implementation would suggest something like

public static void doOperation(D d) { 
    d.printE(System.out); 
}

This way, the utility component doesn't change if C or E change.

The thing is that the utility component, should not be aware of the D' innards.

Having each method in different components might contribute to fulfil with LoD, however, we would have to weight the tradeoffs of such division.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.