Category : SOLID | Sub Category : SOLID Principles | By Prasad Bonam Last updated: 2024-01-10 09:38:15 Viewed : 157
The Interface Segregation Principle (ISP) is one of the SOLID principles of object-oriented design. It suggests that a class should not be forced to implement interfaces it does not use. In other words, a class should only be required to implement the methods that are relevant to its behavior. This helps in preventing classes from being burdened with unnecessary methods.
Let`s consider an example to illustrate the Interface Segregation Principle. Suppose we have an interface called Worker
that includes methods for both manual and automated tasks:
javapublic interface Worker {
void doManualWork();
void doAutomatedWork();
}
Now, let`s say we have two classes that implement this interface: ManualWorker
and AutomatedWorker
.
javapublic class ManualWorker implements Worker {
@Override
public void doManualWork() {
// Implement manual work
}
@Override
public void doAutomatedWork() {
// Not applicable to manual worker, but still required to implement
}
}
public class AutomatedWorker implements Worker {
@Override
public void doManualWork() {
// Not applicable to automated worker, but still required to implement
}
@Override
public void doAutomatedWork() {
// Implement automated work
}
}
In this example, both ManualWorker
and AutomatedWorker
are forced to implement methods that are not relevant to their respective tasks. This violates the Interface Segregation Principle because each class should only be required to implement methods that are specific to its functionality.
To adhere to the ISP, we can refactor the interface into two separate interfaces - one for manual work and one for automated work:
javapublic interface ManualWorker {
void doManualWork();
}
public interface AutomatedWorker {
void doAutomatedWork();
}
Now, the classes can implement only the interface relevant to their functionality:
javapublic class ManualWorker implements ManualWorker {
@Override
public void doManualWork() {
// Implement manual work
}
}
public class AutomatedWorker implements AutomatedWorker {
@Override
public void doAutomatedWork() {
// Implement automated work
}
}
By doing this, we have segregated the interfaces based on functionality, adhering to the Interface Segregation Principle. Each class is now only forced to implement methods that are relevant to its specific role.