Interface Segregation Principle (ISP)
Satya Prakash Chhikara
.NET 8 | .NET Core | ASP.NET | MVC | Software Development | Mobile Development | Web Development | ERP | CMS | Microsoft Technologies | AI Automation | DevOps | AWS | Azure
Interface Segregation Principle (ISP)
Let’s consider a real-life example, your office manager is throwing a party to all team members. You all went to a restaurant and your manager ordered food of his choice only for all team members. Would you like it? NO, because you are being forced to eat food which you don’t like to eat. So, usually in such parties the manager asks everyone’s choice and order food item accordingly, correct. That’s exactly what ISP is which says a class shouldn’t be forced to implement irrelevant functions/methods.
The Interface Segregation Principle (ISP) states that a class shouldn’t be forced to implement an interface method which class don’t use/own. ISP discourages user to create large interface.
Let’s try to understand by an example
In every single project, we need to deal with data base, and we make various classes/interfaces to perform data operation.
To achieve this, we have created an interface “IDataItem” and declare various methods as shown below
?
We made a class “User” and inherited from “IDataItem” like below
?
?
So far everything looks good. ?
In our project, we have a table “MasterCountry” which holds master data for countries. We don’t have any front-end page to insert, update Country table, we have inserted those using DML as we know these are not going to be changed so frequently. Same applies to other master tables as well.
?
领英推荐
But as per current design “MasterCountry” class is being forced to implement “Delete”, “Insert”, “Updated”.
?
As per ISP, this design is not correct. We need to split “IDataItem” interfaces into multiple interfaces and derived class should inherit only interfaces meet respective need.
So, lets split “IDataItem”
?
?
Now, “User” class will inherit both interfaces like below
?
But “MasterCountry” should only inherit interface “IDataItemSelect”
?
?Benefits
Using the ISP in C# enables us to create interfaces tailored to specific client requirements. By avoiding the violation of ISP, we can build more flexible, modular, and maintainable code. Breaking down large interfaces into smaller, cohesive ones reduces coupling and improves code organization.
?