문제

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();
}
도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 softwareengineering.stackexchange
scroll top