Interface Segregation: small contracts for real capabilities

A BasicPrinter only promises to print. It is not forced to implement a Scan() it cannot do.

Time O(1)Space O(1)Code C#, Java, C++ and Python
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.

The idea

Interface Segregation means splitting a broad interface into small, focused ones so a class only has to promise what it can really do. PrintDocument needs only IPrinter. BasicPrinter implements just that — it is never forced to write a Scan() method it cannot support.

Code

static void PrintDocument(IPrinter printer) =>
    printer.Print();

PrintDocument(new BasicPrinter());

interface IPrinter {
    void Print();
}
interface IScanner {
    void Scan();
}
class AllInOnePrinter : IPrinter, IScanner {
    public void Print() { }
    public void Scan() { }
}
class BasicPrinter : IPrinter {
    public void Print() { }
}
interface Printer {
    void print();
}
interface Scanner {
    void scan();
}
class AllInOnePrinter implements Printer, Scanner {
    public void print() { }
    public void scan() { }
}
class BasicPrinter implements Printer {
    public void print() { }
}

class Main {
    static void printDocument(Printer printer) {
        printer.print();
    }

    public static void main(String[] args) {
        printDocument(new BasicPrinter());
    }
}
class Printer {
public:
    virtual void print() = 0;
    virtual ~Printer() = default;
};
class Scanner {
public:
    virtual void scan() = 0;
    virtual ~Scanner() = default;
};
class AllInOnePrinter : public Printer, public Scanner {
public:
    void print() override {}
    void scan() override {}
};
class BasicPrinter : public Printer {
public:
    void print() override {}
};

void printDocument(Printer& printer) {
    printer.print();
}

int main() {
    BasicPrinter basic;
    printDocument(basic);
}
from typing import Protocol

class Printer(Protocol):
    def print(self) -> None: ...

class Scanner(Protocol):
    def scan(self) -> None: ...

class AllInOnePrinter:
    def print(self) -> None: pass
    def scan(self) -> None: pass

class BasicPrinter:
    def print(self) -> None: pass

def print_document(printer: Printer) -> None:
    printer.print()

print_document(BasicPrinter())

Tips

In the .NET library

Split interfaces by what each caller actually needs, not to make every interface as small as possible. One method per interface is not a rule — grouping real, related capabilities is fine.