Interface Segregation Principle (ISP)

The Interface Segregation Principle (ISP) emphasizes that client-specific interfaces should be favored over large, monolithic interfaces. In essence, it discourages creating interfaces with more methods than a client needs. The goal is to avoid forcing clients to implement methods they don’t use, which can lead to unnecessary complexity and code bloat.

The Interface Segregation Principle (ISP) is the fourth SOLID principle after:

To understand ISP better, let’s consider an example involving a Document interface that represents various document types like TextDocument, PDFDocument, and SpreadsheetDocument. Initially, we might create a single, comprehensive Document interface:

interface Document
{
    public function open();
    public function save();
    public function print();
}

While this seems practical, it can become problematic when clients, such as a simple text editor, don’t require the ability to print documents. Following ISP, we can refine our design by creating more specific interfaces that cater to the needs of each client:

interface Openable
{
    public function open();
}

interface Savable
{
    public function save();
}

interface Printable
{
    public function print();
}

Now, our TextDocument class can implement only the Openable and Savable interfaces:

class TextDocument implements Openable, Savable
{
    public function open()
    {
        // Open the text document
    }

    public function save()
    {
        // Save changes to the text document
    }
}

In contrast, the PDFDocument class can implement the Openable, Savable, and Printable interfaces:

class PDFDocument implements Openable, Savable, Printable
{
    public function open()
    {
        // Open the PDF document
    }

    public function save()
    {
        // Save changes to the PDF document
    }

    public function print()
    {
        // Print the PDF document
    }
}

By adhering to ISP, we create more granular, client-specific interfaces, which promotes flexibility. Clients can now implement only the interfaces they need, reducing unnecessary dependencies and complexity. This not only improves code clarity but also ensures that changes or additions to one client’s requirements won’t impact other clients unnecessarily.

In the next post, we’ll explore the Dependency Inversion Principle (DIP), which advocates the decoupling of high-level and low-level modules.

Leave a Comment