Problem Statement
When a single interface forces clients to depend on methods they do not use, it leads to bloated implementations and fragile code. This causes unnecessary coupling and makes the system harder to maintain and extend.
This diagram shows clients depending only on the interfaces they need, each implemented separately, avoiding unnecessary method dependencies.
### Before applying Interface Segregation Principle (violating) class MultiFunctionDevice: def print(self, document): pass def scan(self, document): pass def fax(self, document): pass class OldPrinter(MultiFunctionDevice): def print(self, document): print(f"Printing {document}") def scan(self, document): raise NotImplementedError("Scan not supported") def fax(self, document): raise NotImplementedError("Fax not supported") ### After applying Interface Segregation Principle (applying) from abc import ABC, abstractmethod class Printer(ABC): @abstractmethod def print(self, document): pass class Scanner(ABC): @abstractmethod def scan(self, document): pass class Fax(ABC): @abstractmethod def fax(self, document): pass class SimplePrinter(Printer): def print(self, document): print(f"Printing {document}") class MultiFunctionMachine(Printer, Scanner, Fax): def print(self, document): print(f"Printing {document}") def scan(self, document): print(f"Scanning {document}") def fax(self, document): print(f"Faxing {document}")
Interface Segregation Principle in system design?interface Printer { void print(); }
interface Scanner { void scan(); }
class MultiFunctionDevice implements Printer, Scanner {
public void print() { System.out.println("Printing document"); }
public void scan() { System.out.println("Scanning document"); }
}
MultiFunctionDevice device = new MultiFunctionDevice();
device.print();
device.scan();interface Worker {
void work();
void eat();
}
class Robot implements Worker {
public void work() { System.out.println("Robot working"); }
public void eat() { throw new UnsupportedOperationException(); }
}Pass the test and this pattern moves unknown