单一责任和混合 [英] Single Responsibility and Mixins

查看:156
本文介绍了单一责任和混合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于 Mixins 通常在课堂中引入新的行为,这通常意味着一个类将有多个行为。



如果一个类有一个责任,这被定义为只有一个原因要更改的类。



所以,我可以从两个不同的角度看到这一点。


  1. 。混合模块也只有一个改变的原因。如果课程改变只有类才需要重新测试。如果模块更改只有模块需要重新测试。因此,SRP是完整的。


  2. 课程现在有两个变化的原因。如果班级改变,班级和班级都需要重新测试。如果模块更改,则类和模块同样需要重新测试。 Henge,SRP被违反。


使用mixins是否违反了,最终导致系统更难维护?

当您需要在不相关的类中共享行为(有时您需要)时,基本上有三个选项:


  1. 复制并粘贴到处。这违反了DRY,保证了可维护性。

  2. 将它放入一个抽象类中,让所有的类(其中许多与它们无关)继承自己。这通常被认为是一个OO反模式。简单地说,它完全打破了遗产的概念。只是因为foo和bar做了一些相同的事情,你不会声称这是一个吧 foo is a a bar 。

  3. 把它放在别的地方,名称,并将其混合到需要它的所有类中。

至于测试,我会认为好像一个很好的常规方法一样,应该松散地耦合起来,它和使用它的类可以独立使用。


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

  1. 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.

  2. 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?

解决方案

When you need to share behaviour among unrelated classes (and sometime you need to), there are essentially three options:

  1. Copy and paste everywhere. This violates DRY, is guaranteed to hurt maintainability.
  2. Put it into an abstract class and let all your classes (many of which are unrelated to each other) inherit from it. This is commonly considered an OO antipattern. Simply put, it totally knocks the concept of inheritance on the head. Just because foo and bar do some things the same, you don't claim that foo is-a bar.
  3. Put it somewhere else, give it a clear name, and mix it into all classes that need it.

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.

这篇关于单一责任和混合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆