How do you understand the principle of interface segregation (Interface Segregation Principle)?
sobes.tech AI
Answer from AI
The Interface Segregation Principle (ISP) states that clients should not be forced to depend on interfaces they do not use. It is better to have many small, specific interfaces than one large, universal one.
Applying ISP helps avoid "fat" interfaces that contain too many methods. When a class implements such an interface, it is forced to implement all its methods, even those it does not need. This leads to violation of the Single Responsibility Principle (SRP) and makes classes more fragile and harder to maintain.
Example:
Suppose we have an interface Worker:
// fat interface
interface Worker {
void work();
void sleep();
void eat();
void manage(); // Method not needed by all Workers
}
If we have a class Programmer, it should implement manage(), although programmers usually do not manage others.
Applying ISP:
Split Worker into smaller interfaces:
// segregated interfaces
interface Workable {
void work();
}
interface Sleepable {
void sleep();
}
interface Eatable {
void eat();
}
interface Manageable {
void manage();
}
Now the Programmer class can implement only the interfaces it needs:
// Client depends only on needed interfaces
class Programmer implements Workable, Sleepable, Eatable {
@Override
public void work() {
// ...
}
@Override
public void sleep() {
// ...
}
@Override
public void eat() {
// ...
}
}
And the Manager class implements other interfaces:
class Manager implements Workable, Sleepable, Eatable, Manageable {
@Override
public void work() {
// ...
}
@Override
public void sleep() {
// ...
}
@Override
public void eat() {
// ...
}
@Override
public void manage() {
// ...
}
}
Advantages of ISP:
- Improved flexibility: Classes depend only on the interfaces they need.
- Reduced coupling: Changes in one interface do not affect classes using other interfaces.
- Easier testing: Individual parts of functionality represented by small interfaces can be tested separately.
- Increased maintainability: Smaller, more focused interfaces are easier to understand and modify.
ISP is closely related to other SOLID principles, particularly the Single Responsibility Principle (SRP) and the Liskov Substitution Principle (LSP). It helps create more flexible, reliable, and scalable systems.