Interface Segregation Principle
No client should be forced to depend on methods it does not use. Split a fat interface into small ones, each shaped by one kind of client.
Overview
The Interface Segregation Principle (ISP) is the I in SOLID. Robert C. Martin stated it in his fourth C++ Report column in 1996: clients should not be forced to depend upon interfaces that they do not use. A fat interface is one whose methods fall into groups, each used by a different set of clients. When two clients share one fat interface, a change asked for by one of them reaches the other, even though the other never called the method that changed.
The principle is about the client's point of view. SRP asks what a class should do. ISP asks what a client should have to know. An interface designed from the client side is small, because each client needs only a few methods.
Three terms come up again and again. A fat interface is one interface whose methods serve several unrelated clients. Interface pollution is what happens when a base type is forced to carry methods only some subtypes need. A segregated interface is the cure: one small interface per kind of client.
Where fat interfaces come from
Martin's example is a security system with a Door type that can be locked, unlocked and checked. One kind of door, a timed door, must sound an alarm if it stays open too long, so it registers with a Timer. The Timer calls back through a TimerClient type. The quick fix is to make Door inherit TimerClient, so every door can be a timer client.
The result is a polluted hierarchy. The abstract TimerClient declares time_out(). The abstract Door, with lock(), unlock() and is_open(), now inherits from TimerClient. Both TimedDoor and a PlainDoor inherit from Door, so both carry time_out(). Door now carries a timeout method that most doors never use, and every Door client depends on Timer's callback type.
Now a bug fix in the timer, such as adding a timeout id to the callback, changes TimerClient, which changes Door, which forces every door and every door user to rebuild and retest. A plain door has to carry an empty time_out method. The interface of Door has been polluted by a client it does not serve.
Interview questions
- How do you identify a fat interface that needs splitting?
- How does ISP relate to the other SOLID principles?
- How do you apply ISP in Python, which has no interface keyword?
- What is the difference between a role interface and a header interface?
- When does having many small interfaces become a problem?
Sign up free to read the full topic
More Low-Level Design topics
Start free on Cariara · Coding problems · System design studio