Small interfaces
After this: Split a machine interface that forces an old printer to fake scan and fax into two small ones.
On this page · 5 sections · 3 checks
An office has machines that print, scan and send faxes. A programmer writes one interface for "an office machine" with all three methods. Then the office adds an old printer that can only print. In the last lesson a child class broke a promise its parent made. Here an interface forces a class to make promises it cannot keep.
One interface for everything
from abc import ABC, abstractmethod
class FatMachine(ABC): @abstractmethod def print_page(self, text): pass
@abstractmethod def scan(self): pass
@abstractmethod def fax(self, number): pass
class FatOldPrinter(FatMachine): def print_page(self, text): return "printing " + text
def scan(self): raise NotImplementedError("this printer cannot scan")
def fax(self, number): raise NotImplementedError("this printer cannot fax")
p = FatOldPrinter()print(p.print_page("menu"))try: print(p.scan())except NotImplementedError as e: print("error:", e)printing menu error: this printer cannot scan
interface FatMachine { String printPage(String text); String scan(); String fax(String number);}
class FatOldPrinter implements FatMachine { public String printPage(String text) { return "printing " + text; }
public String scan() { throw new UnsupportedOperationException("this printer cannot scan"); }
public String fax(String number) { throw new UnsupportedOperationException("this printer cannot fax"); }}
public class Main { public static void main(String[] args) { FatMachine p = new FatOldPrinter(); System.out.println(p.printPage("menu")); try { System.out.println(p.scan()); } catch (UnsupportedOperationException e) { System.out.println("error: " + e.getMessage()); } }}printing menu error: this printer cannot scan
- FatOldPrinter implements FatMachine
FatMachine lists three methods: print_pageprintPage, scan and fax. FatOldPrinter wants to be a FatMachine, so that the office code can use it, but it can only print. The interface makes it write all three methods anyway, so it writes the two it cannot do as methods that raise an error. Python code often raises NotImplementedError for that.UnsupportedOperationException is the usual error for that in Java.
Follow the program:
- Printing the menu works:
printing menu. scanis a method the printer has, so any code may call it. It raises the error, and the program printserror: this printer cannot scan.
The class says "I can scan" and then refuses. Code that trusts the interface finds out only when the program runs. And when the interface grows a fourth method, say for stapling, every machine must add one more method, even the ones that will never staple.
Small interfaces
The rule: no class should be forced to promise methods it cannot do. Split a big interface into small ones, and let each class take the ones it can keep. This is the , the I of SOLID. Segregation means keeping things apart.
- OldPrinter implements Printer
- OfficeMachine implements Printer
- OfficeMachine implements PageScanner
from abc import ABC, abstractmethod
class Printer(ABC): @abstractmethod def print_page(self, text): pass
class PageScanner(ABC): @abstractmethod def scan(self): pass
class OldPrinter(Printer): def print_page(self, text): return "printing " + text
class OfficeMachine(Printer, PageScanner): def print_page(self, text): return "printing " + text
def scan(self): return "scanned 1 page"
devices = [OldPrinter(), OfficeMachine()]for d in devices: print(d.print_page("menu"))names = []for d in devices: if isinstance(d, PageScanner): names.append(type(d).__name__)print(", ".join(names))printing menu printing menu OfficeMachine
import java.util.ArrayList;import java.util.List;
interface Printer { String printPage(String text);}
interface PageScanner { String scan();}
class OldPrinter implements Printer { public String printPage(String text) { return "printing " + text; }}
class OfficeMachine implements Printer, PageScanner { public String printPage(String text) { return "printing " + text; }
public String scan() { return "scanned 1 page"; }}
public class Main { public static void main(String[] args) { List<Printer> devices = List.of(new OldPrinter(), new OfficeMachine()); for (Printer d : devices) { System.out.println(d.printPage("menu")); } List<String> names = new ArrayList<>(); for (Printer d : devices) { if (d instanceof PageScanner) { names.add(d.getClass().getSimpleName()); } } System.out.println(String.join(", ", names)); }}printing menu printing menu OfficeMachine
Walk through it:
Printerhas one method, print_pageprintPage.PageScannerhas one,scan. It is not calledScanner, because Java already hasjava.util.Scanner, the class that reads input.OldPrinterimplements onlyPrinter. It has noscanat all, so no code can call one by mistake.OfficeMachineimplements both. A class may implement two interfaces: Python lists two parents, class OfficeMachine(Printer, PageScanner).Java writes implements Printer, PageScanner.- Both machines print the menu. Then the program asks each one whether it is a
PageScanner(isinstanceinstanceof answers that question). OnlyOfficeMachineis, so the last line isOfficeMachine.
Code that needs to scan can now ask for a PageScanner. Python does not check types before the program runs, but an OldPrinter no longer claims to scan: it is not a PageScanner, and it has no scan method.Java refuses to compile a call that passes an OldPrinter where a PageScanner is needed.
Run it
Add a second OldPrinter() to the list and run it again. One more line says printing menu, and the last line stays OfficeMachine.
Check yourself
A new Photocopier can print and scan, but cannot fax. In the design with small interfaces, what does it do?
Which sign tells you that an interface is too big?
Three devices, and a list of the ones that can scan. What does this print?
from abc import ABC, abstractmethod
class Printer(ABC): @abstractmethod def print_page(self, text): pass
class PageScanner(ABC): @abstractmethod def scan(self): pass
class OldPrinter(Printer): def print_page(self, text): return "printing " + text
class OfficeMachine(Printer, PageScanner): def print_page(self, text): return "printing " + text
def scan(self): return "scanned 1 page"
devices = [OldPrinter(), OfficeMachine(), OldPrinter()]scanners = []for d in devices: if isinstance(d, PageScanner): scanners.append(d)print(len(devices), len(scanners))print(scanners[0].scan())import java.util.ArrayList;import java.util.List;
interface Printer { String printPage(String text);}
interface PageScanner { String scan();}
class OldPrinter implements Printer { public String printPage(String text) { return "printing " + text; }}
class OfficeMachine implements Printer, PageScanner { public String printPage(String text) { return "printing " + text; }
public String scan() { return "scanned 1 page"; }}
public class Main { public static void main(String[] args) { List<Printer> devices = List.of(new OldPrinter(), new OfficeMachine(), new OldPrinter()); List<PageScanner> scanners = new ArrayList<>(); for (Printer d : devices) { if (d instanceof PageScanner scanner) { scanners.add(scanner); } } System.out.println(devices.size() + " " + scanners.size()); System.out.println(scanners.get(0).scan()); }}When not to bother
- Say the interface segregation principle: no class should be forced to have methods it cannot do.
- Spot the sign of a too-big interface: a class that fills some of its methods with errors raised on purpose.
- Split a big interface into small ones, Printer and PageScanner, and let each class take the ones it can keep.
- Say that a class may implement two interfaces, and that size alone does not make an interface too big.