DEV Community

Cover image for Interface Segregation Principle (ISP)
Ahmed Raza Idrisi
Ahmed Raza Idrisi

Posted on

Interface Segregation Principle (ISP)

Interface Segregation Principle (ISP)

this topic is easy to understand and help us to develop code with loose coupled and more reusable

๐Ÿ”น Understand ISP

๐Ÿ‘‰ Definition:
Clients should not be forced to depend on interfaces they do not use.

A fat interface = an interface with too many methods.

A role-specific interface = smaller, focused interfaces.

โš ๏ธ Violation Example (fat interface):

interface Worker {
    public function work();
    public function eat();
    public function sleep();
}

class Robot implements Worker {
    public function work() {
        echo "Robot is working";
    }

    // โŒ Robot doesnโ€™t eat or sleep, but is forced to implement these
    public function eat() {
        throw new Exception("Robots donโ€™t eat");
    }

    public function sleep() {
        throw new Exception("Robots donโ€™t sleep");
    }
}

Enter fullscreen mode Exit fullscreen mode

๐Ÿ’ก Problem: Robot depends on methods it doesnโ€™t need โ†’ ISP violation.

โœ… Fix with role interfaces:

interface Workable {
    public function work();
}

interface Eatable {
    public function eat();
}

interface Sleepable {
    public function sleep();
}

class Human implements Workable, Eatable, Sleepable {
    public function work() { echo "Human works"; }
    public function eat() { echo "Human eats"; }
    public function sleep() { echo "Human sleeps"; }
}

class Robot implements Workable {
    public function work() { echo "Robot works"; }
}

Enter fullscreen mode Exit fullscreen mode

Now, each class only implements what it needs ๐Ÿ‘

๐Ÿ”น Refactor Example in Laravel

Letโ€™s apply ISP in a Laravel context.

โš ๏ธ Bad (Fat Interface):

interface NotificationInterface {
    public function sendEmail($message);
    public function sendSMS($message);
    public function sendPush($message);
}

class EmailNotification implements NotificationInterface {
    public function sendEmail($message) { echo "Email: $message"; }
    public function sendSMS($message) { throw new Exception("Not supported"); }
    public function sendPush($message) { throw new Exception("Not supported"); }
}

Enter fullscreen mode Exit fullscreen mode

โœ… Good (Role Interfaces):

interface EmailNotifiable {
    public function sendEmail($message);
}

interface SMSNotifiable {
    public function sendSMS($message);
}

interface PushNotifiable {
    public function sendPush($message);
}

class EmailNotification implements EmailNotifiable {
    public function sendEmail($message) { echo "Email: $message"; }
}

class SMSNotification implements SMSNotifiable {
    public function sendSMS($message) { echo "SMS: $message"; }
}

class PushNotification implements PushNotifiable {
    public function sendPush($message) { echo "Push: $message"; }
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)