Interface Segregation Principle
The Interface Segregation Principle states that no client should be forced to depend on methods it does not use.
Do not add additional functionality to an existing interface by adding new methods. Instead, create a new interface and let your class implement multiple interfaces if needed.
Interface Segregation Principle Example
Let’s take a look at an example of how to write a piece of code that violates this principle.
interface IPost { void CreatePost(); } interface IPostNew { void CreatePost(); void ReadPost(); }
In this example, let’s pretend that I first created IPost interface with the signature of a CreatePost() method. Later on, I modify this interface by adding a new method ReadPost(), so it becomes like the IPostNew interface. This is where we violate the Interface Segregation Principle.
Instead, simply create a new interface.
interface IPostCreate { void CreatePost(); } interface IPostRead { void ReadPost(); }
If any class might need both the CreatePost() method and the ReadPost() method, it will implement both interfaces.