Card 01/ 08
Interface Segregation: Small Interfaces Shaped by Their Clients
A robot should not have to write an eat() method just to join the assembly line.
The interface segregation principle says that no class should be forced to depend on methods it does not use. In practice it means designing interfaces around the code that calls them, so each caller sees only the methods it needs. This card explains the two kinds of harm a large interface does, and how to shape one by its clients.
An interface lists methods a class promises to provide. A client of an interface is any code that calls it, such as a function that takes a Worker and calls its methods. Robert C. Martin described the principle in 1996, after seeing a printer system at Xerox where one huge job class was used by every part of the software.
A large interface harms two groups. The first is implementers. If Worker declares work, eat and sleep, a Robot that only works must still write eat and sleep, and its only honest option is to raise an error or do nothing. That forced method is a Liskov violation waiting for a caller. The second group is clients. A function that only calls work still depends on the whole Worker interface, so a change to sleep forces it to be recompiled, retested or at least re-read.
The diagram shows the result: the assembly line depends only on Workable, the lunch break only on Feedable, and the robot implements only what it can do. Solid arrows are calls; dotted arrows are implementations.
A universal remote is a fair picture. It has buttons for the television, the sound bar and a DVD player you no longer own, and most of them do nothing. The analogy breaks in one place: a useless button can be ignored, while a forced method must be written, tested and kept working by someone.
← → move through sections and cards