Interface Segregation Principle (ISP)

Verze:

02. 07. 2025

Zodpovědná osoba:

Dominik Šlechta

Rule

A client should not be forced to depend on interfaces it does not use.

Description

The Interface Segregation Principle (ISP) advocates for creating specific, narrow interfaces rather than broad, general ones. This reduces the risk of unnecessary dependencies and promotes a cleaner design by ensuring clients only depend on the methods they require. By creating fine-grained interfaces, the system becomes more flexible and maintainable.

Benefits

  • Promotes Modularity: Smaller interfaces lead to fewer dependencies and less impact when changes occur.

  • Improves Flexibility: Clients implement only the necessary methods, avoiding unnecessary code.

  • Reduces Coupling: Smaller, focused interfaces allow systems to remain loosely coupled.

Example (Correct):

interface Printable {
    public function print();
}

interface Scannable {
    public function scan();
}

class Printer implements Printable {
    public function print() {
        // Print logic
    }
}

class Scanner implements Scannable {
    public function scan() {
        // Scan logic
    }
}

Example (Incorrect):

interface MultiFunctionDevice {
    public function print();
    public function scan();
}

class Printer implements MultiFunctionDevice {
    public function print() {
        // Print logic
    }

    public function scan() {
        throw new Exception("Printer can't scan!");
    }
}