Single responsability vs Interface segregation

I stumbled upon a Reddit post forwarding an article about how single responsability and interface segregation would be essentially the same. I obviously disagreed but by reading the comments, it appeared that the differences between the two aren’t that clear for some

Let’s start with the single responsability. It means that a class has one and one reason for change only. Regardless of dependencies or things that it uses. The reason for change cannot be external. In reality it’s not entirely possible especially if the signature of a method changes in a dependency, but the idea is there.

The interface segregation means that interfaces should be small and very specific instead of using one big interface. This will allow also to reduce the risk of having a method signature change that would require a change in a class using that interface.

The interface segregation respects indeed the single responsability principle but is about interfaces and them being very specific in what they do. Like in his example in his book, Uncle Bob (Robert C. Martin) explains how from an interface that does a lot, it splits it in smaller interfaces that manage money withdrawal, money deposit, etc.

You could very well have one class that respects the single responsibility but whose interface will be extensive and violates the interface segregation. So the idea would be to have a class implementing different interfaces so the classes using the interfaces would only use the needed methods.

Another example would be a repository class that has read and write methods but implementing two interfaces, IRepositoryRead and IRepositoryWrite. That way, any client will use either interface or both, but the interfaces will be small and specific thus agreeing with the interface segregation but the Repository class will also agree with the Single Responsability pattern.

Leave a Reply

Your email address will not be published. Required fields are marked *