数据模型对象的Demeter法则

数据模型对象的Demeter法则

本文介绍了数据模型对象的Demeter法则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我昨天从假期回来工作,在我们的日常座谈中,我的队友提到他们正在重构我们的java代码中的所有模型对象,以删除所有的getter和setter,并使模型字段变为所有公共对象,调用因为

我承认我必须刷清我对LoD的了解,但对于我来说,我找不到任何东西表明这是在法律的精神范围内。我们的模型中没有一个getter / setter包含任何业务逻辑,这是他做这样做的理由,所以这些对象的客户端不必了解在get / set方法中是否有一些业务逻辑被执行。 / p>

我认为这是对需要对象结构的内部知识的意义的误解,或者至少是将其字面意义上的打破了一个漂亮的标准惯例在过程中。



所以我的问题是,它是否真的有意义的暴露模型对象的内部结构,而不是通过getter / setter以LoD的名义?

解决方案

罗伯特·马丁有一本名为清洁代码的书籍,涵盖了这一点。



在第6章(对象和数据结构)中,他讨论了对象和数据结构之间的根本区别。
对象受益于封装,数据结构不会。



有关于Demeter法则的一节:

Bob叔叔给出了违反LoD的一个例子:

  final String outputDir = ctxt.getOptions()。getScratchDir()。getAbsolutePath(); 





  final String outputDir = ctxt.options.scratchDir.absolutePath; 

所以这可能是同事来的地方。我认为我们必须这样做,因为LoD这个论点是不精确的。中心问题不在于API是由对象还是数据结构组成。当有更多紧迫的事情要做时,看起来似乎是一个不必要的,容易出错的变化。


I came back to work from vacation yesterday, and in our daily standup, my teammates mentioned they were refactoring all of the model objects in our java code to remove all getters and setters and make the model fields all public objects instead, invoking the Law of Demeter as the reason for doing so because

I admit I had to brush up on my knowledge of the LoD, but for the life of me I can't find anything to indicate that this is within the spirit of the law. None of the getters/setters in our models contain any business logic, which is his justification for doing this so clients of these objects don't have to understand whether or not there is some business logic being executed within the get/set methods.

I think this is a misunderstanding of what it means to need 'internal knowledge of an objects structure', or at the very least is taking it too literally and breaking a pretty standard convention in the process.

So my question is, does it actually make any sense to expose model objects internal structure directly instead of via getters/setters in the name of the LoD?

解决方案

There is a book called Clean Code by Robert Martin that covers this.

In Chapter 6 (Objects and Data Structures) he talks about fundamental differences between objects and data structures.Objects benefit from encapsulation, data structures don't.

There is a section about the Law of Demeter:

Uncle Bob gives an example of a LoD violation:

final String outputDir = ctxt.getOptions().getScratchDir().getAbsolutePath();
final String outputDir = ctxt.options.scratchDir.absolutePath;

So this is probably where your co-workers are coming from. I think the argument "we have to do this because LoD" is imprecise at best. The central issue isn't LoD so much as whether the API consists of objects or data structures. It does seem like an unnecessary and error-prone change to push through when there are more pressing things to do.

这篇关于数据模型对象的Demeter法则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-02 00:53