githubEdit

Interface Segregation

A client should not be forced to depend on methods it does not use.

Explanation: Instead of having large interfaces, break them into smaller, more specific ones.

Java Example

Bad Design (Violating ISP)

interface Worker {
    void work();
    void eat();
}

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

    public void eat() {  // Robots don't eat, but are forced to implement this method.
        throw new UnsupportedOperationException("Robots don't eat");
    }
}

Good Design (Following ISP)

Now, Robot is not forced to implement eat().


Python Example

Bad Design (Violating ISP)

👎 Problem: The Robot class is forced to implement eat(), even though it doesn’t make sense.

Good Design (Following ISP)

👍 Fix: Now, Robot implements only what it needs.

Last updated