了解德米特定律

发布于 2025-01-10 22:23:01 字数 686 浏览 2 评论 0 原文

我试图理解 OOP 背后的 SOLID 原则,但遇到了这个疑问。

类图

按照前面的类图,我将计算车辆的 base_cost。为此,我需要访问马力和税收,然后使用 base_cost() 函数计算所有内容。

伪代码

根据我的理解link 我可以猜测它并不违反德米特定律,因为您正在访问本地创建的类(车辆)中的方法。我说得对吗?

I'm trying to understand the SOLID principles behind OOP and came across with this doubt.

Class Diagram

Following the previous class diagram, I am going to calculate the base_cost for a Vehicle. For such, I need to access the horsepower and the tax and then calculate everything with the base_cost() function.

Pseudocode

From what I understood in this link I could guess that it DOES NOT violate Demeter's law since you are accessing methods from a class created locally (Vehicle). Am I right?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

红玫瑰 2025-01-17 22:23:01

正如评论中所述,SOLID包括德米特定律。这是一个耻辱,因为 它比所有 SOLID 建议更中肯、更有用。只是为了解决这个问题。

关于您的具体情况,Demeter 当然允许调用车辆上的方法,因为该对象被保存为实例变量。对此有明确的规则。

但是,如果我们考虑的是面向对象的系统,则 get_price()get_power()get_tax 返回的内容()也是对象,因为在面向对象系统中一切都应该是对象。在德米特法则上下文中,将返回值相乘就是“向这些对象发送消息”。现在这是不允许的,因为您不直接保存对那些对象的引用,它们也不是参数,也不是在此调用中创建的。

因此,虽然根据德米特定律,“获取”对象/值在技术上可能是合法的,但对您获取的那些对象/值调用方法则不然。所以基本上任何有“吸气剂”的东西最终都会违反德墨忒尔定律。

这是故意的。德墨忒尔定律实际上强制执行的是封装。您不想从对象中“获取”数据,而是希望要求对象使用其拥有的数据执行行为。

As stated in the comments, SOLID does not include the Law of Demeter. Which is a shame, because it is much more pertinent and useful than all of the SOLID suggestions. Just to get that out of the way.

Regarding your exact case, calling methods on the vehicle is of course allowed by Demeter, because that object is held as an instance variable. There is an explicit rule for that.

However, if we're thinking about an object-oriented system, things returned by get_price(), get_power() and get_tax() are also objects, since everything is supposed to be an object in an OO system. In Law of Demeter context, multiplying the returned values is "sending messages" to those objects. Now this is not allowed, since you don't directly hold references to those objects nor are they parameters nor created in this call.

So, while "getting" objects/values might be technically legal according to the Law of Demeter, calling methods on those objects/values that you got are not. So basically anything that has "getters" will eventually violate the Law of Demeter.

This is on purpose. What the Law of Demeter actually enforces is encapsulation. The idea that you don't want to "get" data out of an object, instead you want to ask the object to perform behavior using the data it has.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文