The Interface Segregation Principle (ISP) is one of the five SOLID principles of object-oriented design and development. In Java, the ISP promotes the idea that:
"No client should be forced to depend on methods it does not use."
This means interfaces should be specific and fine-grained rather than large and general. Clients should not be required to implement methods they don't need.
🔧 Why It Matters
If an interface has too many methods, implementing classes may end up with empty or meaningless method implementations, which leads to rigid, fragile, and hard-to-maintain code.
✅ Good Example – Following ISP
interface Printer {
void print(String content);
}
interface Scanner {
void scan(String document);
}
class CanonPrinter implements Printer {
@Override
public void print(String content) {
System.out.println("Printing: " + content);
}
}
class CanonScanner implements Scanner {
@Override
public void scan(String document) {
System.out.println("Scanning: " + document);
}
}
Here, a class only implements the interface it actually needs, promoting separation of concerns.
❌ Bad Example – Violating ISP
interface MultiFunctionDevice {
void print(String content);
void scan(String document);
void fax(String document);
}
class OldPrinter implements MultiFunctionDevice {
@Override
public void print(String content) {
System.out.println("Printing: " + content);
}
@Override
public void scan(String document) {
// Not supported
throw new UnsupportedOperationException("Scan not supported");
}
@Override
public void fax(String document) {
// Not supported
throw new UnsupportedOperationException("Fax not supported");
}
}
Here, OldPrinter
is forced to implement methods it doesn't support. This violates ISP.
✅ Solution with ISP using Interface Composition
interface Printer {
void print(String content);
}
interface Scanner {
void scan(String document);
}
interface Fax {
void fax(String document);
}
class ModernPrinter implements Printer, Scanner, Fax {
@Override
public void print(String content) {
System.out.println("Printing: " + content);
}
@Override
public void scan(String document) {
System.out.println("Scanning: " + document);
}
@Override
public void fax(String document) {
System.out.println("Faxing: " + document);
}
}
Summary
- ISP encourages creating smaller, specific interfaces.
- Helps in building decoupled, modular, and easy-to-maintain code.
- Supports flexibility and clean architecture.
0 comments:
Post a Comment