假设你有类似于以下(可悲的是,我不能发布原码):此方法调用是否违反Demeter法则?
public void foo() {
MyObject obj = getMyObject();
bar(obj);
}
public void bar(MyObject obj) {
Type type = new Type(obj.getOtherObject());
}
foo
电话bar
,通过在obj
。但不是使用obj
,而是调用getter来检索所需的信息。这是否违反了德米特法?
它会更好写的是这样的:根据对Law of Demeter维基
public void foo() {
MyObject obj = getMyObject();
bar(obj.getOtherObject());
}
public void bar(MyOtherObject otherObj) {
Type type = new Type(otherObj);
}