The Interface Segregation Principle (ISP) is another principle of the SOLID acronym, a set of five principles of object-oriented programming and design. The principles make it easier to develop software that is easy to manage and maintain, and also to understand.
The Interface Segregation Principle states that clients should not be forced to depend on interfaces they do not use. In other words, it's about making fine-grained interfaces that are client-specific rather than having a single general-purpose interface.
This principle helps to keep a system decoupled and thus easier to refactor, change, and redeploy. It leads to more robust, less error-prone code.
Let's look at a simple example:
Suppose you have a Printer
interface that declares methods print()
, fax()
, and scan()
. If you create a class InkjetPrinter
that implements this interface, you'll have to implement all three methods, even if this printer doesn't support faxing or scanning. This forces the InkjetPrinter
class to depend on methods it doesn't actually use.
According to the Interface Segregation Principle, we should instead have separate interfaces for each function: Printer
, Fax
, and Scanner
. The InkjetPrinter
would implement only the Printer
interface, while a class for a high-end office printer could implement all three interfaces. This way, each class only needs to know about the methods it actually uses.
So, the principle is all about reducing the side effects and frequency of required changes by splitting interfaces that are very large into smaller and more specific ones, so that clients will only have to know about the methods that are of interest to them.