单一职责和混合
鉴于 Mixin 通常会向类中引入新行为,这通常意味着类将具有更多比一种行为。
如果一个类具有单一职责,则这被定义为该类只有一个变更原因。
所以,我可以从两个不同的角度来看这个
类只有一个改变的原因。混入的模块也只有一个变化的原因。如果班级发生变化,则仅需要重新测试班级。如果模块发生变化,则只需重新测试该模块。因此,SRP 保持不变。
班级现在有两个改变的原因。如果类发生变化,类和模块都需要重新测试。如果模块发生更改,则类和模块都需要重新测试。 Henge,SRP 被违反了。
使用 mixin 是否违反单一职责原则,并最终导致系统更难维护?
Given that Mixins generally introduce new behaviour into a class, this generally implies that a class would have more than one behaviour.
If a class has a single responsibility this is defined as the class having only one reason for change.
So, I can see this from two different perspectives
The class only has one reason for change. The module mixed in also has only one reason for change. If the class is changed only the class will need retesting. If the module is changed only the module needs retesting. Hence, SRP is intact.
The class now has two reasons for change. If the class is changed, both class and module need retesting. If the module is changed, again both class and module need retesting. Henge, SRP is violated.
Does the use of mixins violate the Single Responsibility Principle, and ultimately result in a harder to maintain system?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当您需要在不相关的类之间共享行为时(有时您需要这样做),基本上有三个选项:
至于测试,我认为一个“好的”mixin,就像一个好的常规方法一样,应该足够松散地耦合,以便它和使用它的类可以独立使用。
When you need to share behaviour among unrelated classes (and sometime you need to), there are essentially three options:
As for testing, I would argue that a "good" mixin, just like a good regular method, should be coupled loosely enough that it and the classes using it can be used independently.
我认为这取决于 mixin。它很可能会赋予它额外的职责,但是有像 Ruby's Comparable 这样的职责提供相当低级的功能,我认为这不会违反 SRP。
I think it depends on the mixin. It might well give it additional responsibilities, but there are those like Ruby's Comparable which give pretty low-level functionality which I would say doesn't violate SRP.
如果这是真的,那么单一(实现)继承也同样如此。虽然没有人再喜欢 23 层的继承层次结构,但它仍然占有一席之地。
继承不会破坏 SRP 的原因是,它所讨论的类是字面代码文件意义上的类,而不是更抽象的类。如果更改基类代码文件,通常不需要更改该文件。
因此,保留了更改它的唯一原因。
If that was true, it would be equally true of single (implementation) inheritance. While noone likes 23-deep inheritance hierarchies any more, it still has it's place.
The reason inheritance doesn't break the SRP is that the class it is talking about is the class in the sense of a literal code file, not anything more abstract. That file generally doesn't need to change if you change a base class code file.
So the single reason to change it is preserved.
我同意这一点。然而,SRP有时可能(或应该)被违反。
I would agree with that. However, the SRP can (or should) be violated sometimes.