Zack ISSOIR
Zack ISSOIR

Reputation: 974

SOLID , SRP , IComparable

OK, Is implementing IComparable and other interfaces (Like IDisposable) on a single class a violation of the SRP principle .

SRP states that every class should implement a signle responsability and methods should be interconnected in a high degree to achieve cohesive classes .

Isn't comparison another responsability ?

Some clarification would be appreciated.

Upvotes: 4

Views: 226

Answers (2)

yelxe
yelxe

Reputation: 176

I would argue that impementations of IComparable and IDisposable are not responsibilities at all, and therefore would not violate SRP.

In the context of SRP, a responsibility is to an interactor of your system (i.e. a user, role or external system). If your system has a Business Requirements Document, all responsibilities should be at least inferred within the functional or non-functional requirements. If not, ask yourself which business owner is going to ask you to change how an object disposes itself.

On the first project I worked on after learning about SRC, we interpreted it as "one public method per class" and applied it as a hard rule. While that made it easy to stay in "compliance", we ended up with code that was far more complicated than it needed to be.

If your IComparable/IDisposable implementations need to change, that change will be driven by the functional (business) part of your class also requiring change (at the same time and for the same reason).

Upvotes: 3

Arthur Noseda
Arthur Noseda

Reputation: 2654

If I were you I would try to adhere to SRP, but not so strictly as the effort finally becomes counter-productive. So now with that said, what should you do? Either you implement IComparable and have comparison fully encapsulated in the object, or have a separate comparator and implement the comparison logic in it. Now for comparison, as far as SRP is concerned, if the comparison is fairly basic and should not be subject to changes, I would implement IComparable and be done with it. If you can reasonably foresee some changes in the future, or if the comparison is use case-dependent, then I would go the comparator route. The ultimate goal is to develop closed components and make them cooperate by composing them, so if comparison has little chance to change, the component can be closed and you won't hear about it again. You could also comment the use of IComparable in your code, and if some change happens in the future, switch to composing with a comparator, as the change that was said not to happen did indeed happen.

Upvotes: 4

Related Questions