Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 511
Zack ISSOIR Avatar asked Mar 12 '23 09:03

Zack ISSOIR


1 Answers

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.

like image 199
Arthur Noseda Avatar answered Mar 23 '23 11:03

Arthur Noseda