Interface Segregation Principle (ISP or I in SOLID principles) in C#

What is Interface Segregation Principle (ISP)?

The interface segregation principle is one of the SOLID principles that states that the clients should not be compelled to implement an interface that contains declarations of members or operations that they would not need or never use. Such interfaces are known as “fat” or polluted interfaces (also called interface bloat) as they contain too many operations.
Rather than having a fat interface and have the clients consume them, it is a recommended practice to break the fat interface to one or more specific and cohesive interfaces. If your code violates the interface segregation principle, you can fix it by taking advantage of the Adapter design pattern.
Imagine a situation in which the type that implements the interface needs to use only a few methods of the interface but not all. So, implementing such an interface where not all of the methods are relevant to the type implementing the interface is not a good practice.
So, then what’s the solution or alternative? Well, you can break this fat interface into one or more interfaces if you have access to the interface source code. If it is that you have no access to the interface, all you can do is use the relevant methods and just ignore the other ones. You can just throw and instance of the NotImplementedException class from those methods of the interface you don’t need at all. Note that when you are implementing an interface in a class, you must implement all of its members – otherwise the compiler would flag an error.
Generally speaking, if an interface has methods that can be broken into groups, each serving a different set of clients, we say the interface is “fat” and violates ISP. According to SRP, it means the same interface is assuming multiple responsibilities. To solve this problem, the “fat” interface should be replaced with multiple client-specific interfaces.

Copyright © All Rights Reserved - C# Learners