gpt4 book ai didi

ruby - 在处理 Demeter 法则时,由于过度授权而需要更改消费者类的情况的示例是什么?

转载 作者:太空宇宙 更新时间:2023-11-03 16:51:42 24 4
gpt4 key购买 nike

我经常发现自己做了很多 delegating .

Ruby Science ,它说:

Many delegate methods to the same object are an indicator that your object graph may not accurately reflect the real world relationships they represent.

If you find yourself writing lots of delegators, consider changing the consumer class to take a different object. For example, if you need to delegate lots of User methods to Account, it’s possible that the code referencing User should actually reference an instance of Account instead.

这个我不是很懂。这在实践中看起来如何的示例是什么?

最佳答案

我想那一章的作者想说清楚,例如,写:

class User
def discounted_plan_price(discount_code)
coupon = Coupon.new(discount_code)
coupon.discount(account.plan.price)
end
end

注意 account.plan.price,可以通过在用户模型上使用 delegate 来更好地完成,例如:

class User
delegate :discounted_plan_price, to: :account
end

它允许您编写以下内容:

class User
def discounted_plan_price(discount_code)
account.discounted_plan_price(discount_code)
end
end

class Account
def discounted_plan_price(discount_code)
coupon = Coupon.new(discount_code)
coupon.discount(plan.price)
end
end

请注意,由于 delegate,我们写的是 plan.price,而不是 account.plan.price

很好的例子,但还有更多。

关于ruby - 在处理 Demeter 法则时,由于过度授权而需要更改消费者类的情况的示例是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20155350/

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