Interface Segregation Principle (ISP)
The Interface Segregation Principle (ISP) is one of the five object-oriented design principles that form SOLID. It emphasizes that client-specific interfaces are better than one general-purpose interface.
The ISP states that clients should not be forced to depend on interfaces they do not use. Instead, interfaces should be fine-grained and specific to the needs of the client.
To understand the need for the ISP, let's consider an example where we have a Printer
interface and two classes implementing it: SimplePrinter
and AdvancedPrinter
:
1interface Printer {
2 void print(Document document);
3}
4
5class SimplePrinter implements Printer {
6 public void print(Document document) {
7 System.out.println("Printing document " + document.getTitle());
8 }
9}
10
11class AdvancedPrinter implements Printer {
12 public void print(Document document) {
13 System.out.println("Printing document " + document.getTitle() + " with advanced options");
14 }
15}
In this example, the Printer
interface has a single method print
, which takes a Document
object as a parameter. The SimplePrinter
class provides a basic implementation of the printer, while the AdvancedPrinter
class provides a more advanced implementation.
According to the ISP, it is better to have client-specific interfaces for different printing needs, rather than a single general-purpose interface. This allows clients to depend only on the interfaces they need, reducing unnecessary dependencies and making the code easier to understand and maintain.
By following the ISP, we can avoid situations where clients are forced to implement methods they do not need or depend on unnecessary functionality. This promotes loose coupling and allows for better modularization of code.
In the example above, instead of having a single Printer
interface, we could have separate interfaces SimplePrinter
and AdvancedPrinter
, each with their own methods specific to their functionality. This would allow clients to depend only on the interface they need, improving code readability and reducing the impact of changes when new functionalities are added or existing ones are modified.
By applying the ISP, we can design interfaces that are cohesive, minimal, and focused on the needs of the client, resulting in flexible and maintainable code.
xxxxxxxxxx
}
interface Printer {
void print(Document document);
}
class SimplePrinter implements Printer {
public void print(Document document) {
System.out.println("Printing document " + document.getTitle());
}
}
class AdvancedPrinter implements Printer {
public void print(Document document) {
System.out.println("Printing document " + document.getTitle() + " with advanced options");
}
}
class Document {
private String title;
public Document(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
}
public class Main {