Skip to main content

Practical Examples of Interface Segregation Principle

Interface Segregation Principle (ISP)

Practical Examples

Example 1: Good Design

Here is a code snippet showing an interface that adheres to ISP by having smaller, client-specific interfaces:

interface Printer {
void print(Document doc);
}

interface Scanner {
void scan(Document doc);
}

class MultiFunctionPrinter implements Printer, Scanner {
@Override
public void print(Document doc) {
System.out.println("Printing document");
}

@Override
public void scan(Document doc) {
System.out.println("Scanning document");
}
}

class SimplePrinter implements Printer {
@Override
public void print(Document doc) {
System.out.println("Printing document");
}
}

Example 2: Violation

Here is a code snippet where a single interface is overloaded with methods, violating ISP:

interface Machine {
void print(Document doc);
void scan(Document doc);
void fax(Document doc);
}

class MultiFunctionPrinter implements Machine {
@Override
public void print(Document doc) {
System.out.println("Printing document");
}

@Override
public void scan(Document doc) {
System.out.println("Scanning document");
}

@Override
public void fax(Document doc) {
System.out.println("Faxing document");
}
}

class SimplePrinter implements Machine {
@Override
public void print(Document doc) {
System.out.println("Printing document");
}

@Override
public void scan(Document doc) {
// Not implemented
}

@Override
public void fax(Document doc) {
// Not implemented
}
}

Refactor Example 2

Refactor the violating example to split the interface into smaller, client-specific interfaces:

interface Printer {
void print(Document doc);
}

interface Scanner {
void scan(Document doc);
}

interface Fax {
void fax(Document doc);
}

class MultiFunctionPrinter implements Printer, Scanner, Fax {
@Override
public void print(Document doc) {
System.out.println("Printing document");
}

@Override
public void scan(Document doc) {
System.out.println("Scanning document");
}

@Override
public void fax(Document doc) {
System.out.println("Faxing document");
}
}

class SimplePrinter implements Printer {
@Override
public void print(Document doc) {
System.out.println("Printing document");
}
}

By refactoring the large interface into smaller, client-specific interfaces, we adhere to the Interface Segregation Principle, leading to a more modular, maintainable, and flexible design.