What's the Interface Segregation Principle?
- (ISP) suggests that a class should not be forced to implement methods it doesn’t need
- Class should have small, focused interfaces rather than large.
Why use Interface Segregation Principle ?
This helps to avoid unnecessary dependencies and ensures that classes only implement the methods they actually need
Example Description:
I work on application that manage tasks between teams and i want to apply ISP in my code . This post discuss traditional way and advanced way to implement this case .
Example:
- I have created an interface named 'IManageTasks' and defined four functions: 'FollowStatus,' 'CreateTasks,' 'AssignTasks,' and 'WorkingOnTasks.'
public interface IManageTasks
{
void FollowStatus();
void CreateTasks();
void AssignTasks();
void WorkingOnTasks();
}
- I have defined two classes that inherit from 'IManageTasks.' : Developer and TeamLead
internal class Developer : IManageTasks
{
// Below functions not applicable for Developer
public void AssignTasks()
{
// TODO Logic
}
public void CreateTasks()
{
// TODO Logic
}
public void FollowStatus()
{
// TODO Logic
}
// This function applicable for Developer
public void WorkingOnTasks()
{
// TODO Logic
}
}
internal class TeamLead : IManageTasks
{
// Below functions applicable for TeamLead
public void AssignTasks()
{
// TODO Logic
}
public void CreateTasks()
{
// TODO Logic
}
public void FollowStatus()
{
// TODO Logic
}
// This function not applicable for TeamLead
public void WorkingOnTasks()
{
// TODO Logic
}
}
-
I prefer to use the example below as it adheres to the Interface Segregation Principle (ISP).
- I have created two interfaces named 'IDeveloper' and 'ITeamLead,' each containing only the functions that were previously defined
internal class TeamLead : ITeamLeader
{
public void AssignTasks()
{
// TODO Logic
}
public void CreateTasks()
{
// TODO Logic
}
public void FollowStatus()
{
// TODO Logic
}
}
internal class Developer : IDeveloper
{
public void WorkingOnTasks()
{
//TODO Logic
}
}