09 Jan 2025

Interface Segregation Principle (ISP)

Definition:

Clients should not be forced to depend on interfaces they do not use. Instead of one large, general-purpose interface, multiple specific interfaces are preferred.

Explanation:

The Interface Segregation Principle promotes creating narrowly focused interfaces tailored to specific client needs. This reduces the burden on classes to implement unnecessary methods, enhances modularity, and simplifies the implementation process. By avoiding “fat” interfaces, systems become more flexible and easier to maintain.

Example:

Imagine an IMultiFunctionDevice interface that includes methods for printing, scanning, and faxing. A simple printer should not be forced to implement scanning and faxing.

# Violates ISP
class IMultiFunctionDevice:
    def print(self, document):
        pass

    def scan(self, document):
        pass

    def fax(self, document):
        pass

class Printer(IMultiFunctionDevice):
    def print(self, document):
        # Print logic
        pass
    
    def scan(self, document):
        raise NotImplementedError
    
    def fax(self, document):
        raise NotImplementedError

# Adheres to ISP by segregating interfaces
class IPrinter:
    def print(self, document):
        pass

class IScanner:
    def scan(self, document):
        pass

class Printer(IPrinter):
    def print(self, document):
        # Print logic
        pass

class Scanner(IScanner):
    def scan(self, document):
        # Scan logic
        pass

class MultiFunctionDevice(IPrinter, IScanner):
    def print(self, document):
        # Print logic
        pass
    
    def scan(self, document):
        # Scan logic
        pass
← Back to Library