Single Responsibility and Mixes

Given that Mixins typically introduce new behavior into a class, this usually implies that the class will have more than one behavior.

If a class has one responsibility, it is defined as a class having only one reason for the change.

So, I see it from two different sides.

  • A class has only one reason to change. The mixed module also has only one reason for the change. If the class is changed, the class will need to be retested. If the module is modified, the module needs to be retested. Therefore, the SRP is not damaged.

  • The class now has two reasons to change. If the class is changed, both the class and the module need to be retested. If the module is changed, then again both that class and the module need to be retested. Henge, SRP is being violated.

Does the use of mixins affect the principle of shared responsibility and ultimately lead to more difficult to maintain the system?

+6
oop design-patterns mixins srp
source share
4 answers

When you need to share behavior between unrelated classes (and once you need to), there are essentially three options:

  • Copy and paste everywhere. This violates DRY, guaranteed to damage maintainability.
  • Put it in an abstract class and let all your classes (many of which are not related to each other) inherit from it. It is generally considered an antipatter of OO. Simply put, this completely destroys the concept of inheritance on the head. Just because foo and bar do some things the same way, you are not saying that foo is a bar.
  • Put it in another place, give it a clear name, and mix it with all the classes that need it.

As for testing, I would say that a “good” mixin, like a good regular method, should be loosely coupled with the fact that it and the classes it uses can be used independently.

+1
source share

I think it depends on mixin. This may give additional responsibilities, but there are ones like Ruby Comparable that provide fairly low-level functionality, which I would say does not violate SRP.

+1
source share

Given that Mixins typically introduce new behavior into a class, this usually implies that the class will have more than one behavior.

If this were so, this would be equally true for one (implementation) inheritance. While no one else loves the 23-deep inheritance hierarchies, it still holds.

Inheriting the cause does not violate SRP, so that the class he is talking about is a class in the sense of a literal code file, and not something more abstract. Usually this file does not need to be modified if you modify the base class code file.

Thus, the only reason for its change remains.

+1
source share

I agree with it. However, SRP can sometimes (or should) be compromised.

-one
source share

All Articles