Clients should not be obligated to rely on interfaces they don’t utilize.

Example: Consider an interface that imposes irrelevant methods on implementing classes.

// Violation of ISP
public interface Worker {
    void work();
    void eat();
}

public class HumanWorker implements Worker {
    public void work() {
        System.out.println("Human working");
    }

    public void eat() {
        System.out.println("Human eating");
    }
}

public class RobotWorker implements Worker {
    public void work() {
        System.out.println("Robot working");
    }

    public void eat() {
        // Robots don't eat
    }
}

// Following ISP
public interface Workable {
    void work();
}

public interface Eatable {
    void eat();
}

public class HumanWorker implements Workable, Eatable {
    public void work() {
        System.out.println("Human working");
    }

    public void eat() {
        System.out.println("Human eating");
    }
}

public class RobotWorker implements Workable {
    public void work() {
        System.out.println("Robot working");
    }
}

In this scenario, RobotWorker need not implement eat(), thereby adhering to the ISP.

Previous: Liskov Substitution Principle (LSP)

Next: Dependency Inversion Principle (DIP)

SOLID


2 responses to “Interface Segregation Principle (ISP)”

  1. Marlon Avatar
    Marlon

    Your writing has a way of resonating with me on a deep level. It’s clear that you put a lot of thought and effort into each piece, and it certainly doesn’t go unnoticed.

  2. Shailesh Avatar
    Shailesh

    SOLID Principle

Leave a Reply

Your email address will not be published. Required fields are marked *