问题描述
让我们从维基百科开始:
Let's start with Wikipedia:
- O本身
- m的参数
- 在m
- O的直接组件对象中创建/实例化的任何对象
- 一个全局变量,可由O访问,范围为m
- O itself
- m's parameters
- Any objects created/instantiated within m
- O's direct component objects
- A global variable, accessible by O, in the scope of m
规则1:
public class ClassOne {
public void method1() {
method2();
}
public void method2() {
}
}
规则2:
public class ClassOne {
public void method1(ClassTwo classTwo) {
classTwo.method2();
}
}
class ClassTwo {
public void method2() {
}
}
规则3:
public class ClassOne {
public void method1() {
ClassTwo classTwo = new ClassTwo();
classTwo.method2();
}
}
class ClassTwo {
public void method2() {
}
}
规则4(感谢@juharr):
Rule 4 (thanks @juharr):
public class ClassOne {
private ClassTwo classTwo;
public void method1() {
classTwo = new ClassTwo();
classTwo.method2();
}
}
class ClassTwo {
public void method2() {
}
}
规则5:
?
任何人都可以帮我处理规则5吗?
Can anyone help me with Rule 5?
Demeter法律是否意味着链接不好?
And doesn't Law of Demeter imply that chaining is bad?
User.getName().getLastName();
这导致高耦合。
不是告诉,不要问类似的原则吗?
Isn't "Tell, don't ask" a similar principle?
这就是一切吗?我错了什么?你怎么能遵守得墨忒耳法?
So is this everything? Am I wrong about something? How can you obey Law of Demeter?
推荐答案
告诉不要问有点不同。
"Tell don't ask" is a bit different.
Demeter:不要从中得到一些东西来做最后的事情。
Demeter: don't get something to get something from that to do something on the final thing.
TDA:不要从另一个对象中检索信息,然后再做出决定。简单示例:
TDA: don't retrieve "information" from another object to then make a decision on that. Simple example:
if (someList.size() == 0) { bla
vs。
if (someList.isEmpty()) { bla
在这两种情况下,你都在某个其他对象上调用方法;但是有一个关键的区别:第一个调用会向你公开另一个对象的内部状态;然后你做出一些决定。鉴于,在TDA改进的第二版;你把那个状态评估留在另一个对象中;从而以某种方式减少耦合。
In both cases you are calling a method on some other object; but there is a key difference: the first call exposes "internal" state of that other object to you; on which you then make some decision. Whereas, in the "TDA" improved second version; you leave that "status evaluation" within that other object; thereby somehow reducing coupling.
这篇关于什么是得墨忒耳定律?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!