gpt4 book ai didi

ruby-on-rails - 得墨忒耳法则——你能走多远?

转载 作者:行者123 更新时间:2023-12-04 06:33:10 27 4
gpt4 key购买 nike

我想遵循得墨忒耳法则。当我通过我的代码搜索“两个点”时,我发现自己在问是否真的值得在这种类型的上下文中设置委派职责:


class Activity
def increment_user_points!
self.user.increment_points!(points, true)
end
end


module UserDelegator
def user_increment_points!(points, increment_credits=false)
self.user.increment_points!(points, increment_credits)
end
end

class Activity
include UserDelegator

def increment_user_points!
user_increment_points!(points, true)
end
end

你怎么认为?

最佳答案

你的例子没有违反得墨忒耳法则。用户是事件的一个属性,并且您正在访问该用户的公共(public) API 方法,因此您对原始实现没有错误。

得墨忒耳法则的目标是避免破坏对象封装。您的“两点”方法有点过于简化了这个想法。实际上,您应该检查您的对象是如何交互的,并确保您没有对其他对象的属性或关系了解太多。例如,如果以下行为违反规则:

def update_user_address
@user.address.set(new_address)
end

这是因为地址是用户的业务,它应该通过用户的API适本地封装对它的访问。作为用户的客户端,我们不应该直接访问用户属性的 API。

同样,在您的示例中,您直接使用用户 API,这很好,并且没有违反 Demeters Law。综上所述,我发现一般规则是一个很好的遵循。如果您避免破坏对象封装,您的代码通常会更容易更改和维护,并且类将更容易重构,如图所示。

关于ruby-on-rails - 得墨忒耳法则——你能走多远?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6103967/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com