Interface Segregation Principle: Definition and Practical Guide
Interface Segregation Principle means that no client should be forced to depend on methods it does not use. It encourages splitting large interfaces into smaller, specific ones so that classes only implement what they actually need.How It Works
Imagine you have a Swiss Army knife with many tools, but you only need a screwdriver. Carrying the whole knife is bulky and confusing. The Interface Segregation Principle (ISP) suggests creating smaller, focused tools instead of one big tool with everything.
In software, this means breaking down large interfaces into smaller ones that serve specific needs. This way, a class only depends on the methods it actually uses, making the code easier to understand, maintain, and change without affecting unrelated parts.
Example
This example shows a large interface split into smaller ones. Classes implement only the interfaces they need.
from abc import ABC, abstractmethod class Printer(ABC): @abstractmethod def print_document(self, document): pass class Scanner(ABC): @abstractmethod def scan_document(self, document): pass class MultiFunctionPrinter(Printer, Scanner): def print_document(self, document): print(f"Printing: {document}") def scan_document(self, document): print(f"Scanning: {document}") class SimplePrinter(Printer): def print_document(self, document): print(f"Printing: {document}") # Usage printer = SimplePrinter() printer.print_document("My Report") mfp = MultiFunctionPrinter() mfp.print_document("My Report") mfp.scan_document("My Report")
When to Use
Use the Interface Segregation Principle when you notice that interfaces are too large or force classes to implement methods they don't need. This often happens in systems with many features combined in one interface.
For example, in a printer system, some devices only print, while others print and scan. Splitting interfaces helps avoid unnecessary code and makes it easier to add new device types later.
Key Points
- Split large interfaces into smaller, focused ones.
- Clients should only depend on methods they use.
- Improves code maintainability and flexibility.
- Helps avoid forcing unnecessary code on classes.