ISP Interface-Segregation-Principle
Interface Segregation Principle (ISP)
The Interface Segregation Principle (ISP) is one of the five SOLID principles of object-oriented design. It states that no client should be forced to depend on methods it does not use. Instead of having a single large interface, ISP recommends breaking down the interface into smaller, more specific ones, so that clients only need to know about the methods that are of interest to them.
Key Benefits:
- Decoupling: Reduces the dependencies between classes, making the system more modular and easier to maintain.
- Cohesion: Ensures that interfaces are more focused and relevant to the clients that use them.
- Flexibility: Simplifies the implementation of classes by avoiding unnecessary methods.
Example:
Consider an interface Worker
that combines multiple responsibilities.
Violation of ISP:
public interface Worker {
void work();
void eat();
}
A Robot
class that implements Worker
would have to implement eat
method, which is not relevant.
public class Robot implements Worker {
@Override
public void work() {
// Robot working code
}
@Override
public void eat() {
// Irrelevant for Robot
}
}
Adhering to ISP: Separate the interface into more specific ones.
public interface Workable {
void work();
}
public interface Eatable {
void eat();
}
Now, Robot
implements only the relevant interface.
public class Robot implements Workable {
@Override
public void work() {
// Robot working code
}
}
And a HumanWorker
can implement both.
public class HumanWorker implements Workable, Eatable {
@Override
public void work() {
// Human working code
}
@Override
public void eat() {
// Human eating code
}
}
Summary:
The Interface Segregation Principle promotes the creation of fine-grained, specific interfaces that align with the actual needs of clients. By following ISP, developers can create more modular, maintainable, and understandable code, avoiding the pitfalls of large, monolithic interfaces that try to do too much.
Backlinks