Rails allows us to delegate methods to other objects by using simple macro-like syntax. However, I'm in confusion on a particular case.
Rails允许我们使用简单的类宏语法将方法委托给其他对象。然而,我对一个特殊的案例感到困惑。
If I delegate a method to obtain an object and then delegate another method to that new object, will it break the demeter law?
如果我委托一个方法来获得一个对象,然后将另一个方法委托给那个新对象,它会破坏demeter定律吗?
For example, in a Course
class
例如,在课程中
#course.rb
...
belongs_to :batch
...
and it an Exam
class
这是一堂考试课
#exam.rb
...
belongs_to :course
delegate :batch, to: :course
...
# access some batch's method like this
batch.name # which really is course.batch.name
Is it a violation? What could be the possible solution?
这是一个违反吗?可能的解决方案是什么?
1 个解决方案
#1
5
I would argue that delegation (even multiple levels deep) does not violate the Law of Demeter, because you do not actually call the method on the unit two levels away.
我认为委托(甚至多层深度)并不违反Demeter定律,因为你不会在两层之外的单元调用方法。
Delegation improves loose coupled components, because you can replace a delegation in a unit with a method and change its implementation, without other units need to change.
委托改进松耦合组件,因为您可以用方法替换单元中的委托并更改其实现,而不需要更改其他单元。
The law tells you not to depend on the internal of an external object. It is okay to access its values, but through a proper interface. That interface might be - in its most simple form - a delegator.
法律告诉你不要依赖于外部物体的内部。可以通过适当的接口访问它的值。这个接口可能是——以最简单的形式——一个委托。
#1
5
I would argue that delegation (even multiple levels deep) does not violate the Law of Demeter, because you do not actually call the method on the unit two levels away.
我认为委托(甚至多层深度)并不违反Demeter定律,因为你不会在两层之外的单元调用方法。
Delegation improves loose coupled components, because you can replace a delegation in a unit with a method and change its implementation, without other units need to change.
委托改进松耦合组件,因为您可以用方法替换单元中的委托并更改其实现,而不需要更改其他单元。
The law tells you not to depend on the internal of an external object. It is okay to access its values, but through a proper interface. That interface might be - in its most simple form - a delegator.
法律告诉你不要依赖于外部物体的内部。可以通过适当的接口访问它的值。这个接口可能是——以最简单的形式——一个委托。