Introduction
The Interface Segregation Principle (ISP) is the fourth principle in the SOLID principles. It states,
Clients should not be forced to depend on interfaces they do not use.
In other words, instead of creating large, monolithic interfaces, we should create smaller, more specific ones that are relevant to particular clients.
Why is ISP Important?
- Reduces unnecessary dependencies.
- Improves maintainability and readability of code.
- Makes code easier to test and extend.
Violation of ISP – An Example
Consider the following interface.
public interface IMachine {
void Print();
void Scan();
void Fax();
}
public class OldPrinter implements IMachine {
@Override
public void Print() {
// Printing logic
}
@Override
public void Scan() {
throw new UnsupportedOperationException("Scan not supported");
}
@Override
public void Fax() {
throw new UnsupportedOperationException("Fax not supported");
}
}
Problem: The OldPrinter class is forced to implement methods it doesn't support, violating ISP.
How to Fix the Violation?
Break the large interface into smaller, more specific interfaces.
public interface IPrinter {
void Print();
}
public interface IScanner {
void Scan();
}
public interface IFax {
void Fax();
}
public class OldPrinter implements IPrinter {
@Override
public void Print() {
// Printing logic
}
}
public class ModernPrinter implements IPrinter, IScanner, IFax {
@Override
public void Print() {
// Printing logic
}
@Override
public void Scan() {
// Scanning logic
}
@Override
public void Fax() {
// Faxing logic
}
}
Result: Now, each class only depends on the functionality it actually needs, satisfying the Interface Segregation Principle.
Benefits of Applying ISP
- Relevance: Clients only implement methods they use.
- Flexibility: It is Easier to add new interfaces or features independently.
- Scalability: Encourages clean architecture in large-scale systems.
Conclusion
The Interface Segregation Principle is key to building modular and maintainable software. By designing interfaces that are specific to client needs, we improve the robustness and scalability of applications.