什么是得墨忒耳定律? [英] What is Law of Demeter?

查看:383
本文介绍了什么是得墨忒耳定律?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们从维基百科开始:

Let's start with Wikipedia:


更正式地说,函数的Demeter法要求方法 m O 的对象只能调用以下类型对象的方法:

More formally, the Law of Demeter for functions requires that a method m of an object O may only invoke the methods of the following kinds of objects:


  1. O本身

  2. m的参数

  3. 在m

  4. O的直接组件对象中创建/实例化的任何对象

  5. 一个全局变量,可由O访问,范围为m

  1. O itself
  2. m's parameters
  3. Any objects created/instantiated within m
  4. O's direct component objects
  5. 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.

这篇关于什么是得墨忒耳定律?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆