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");
}
}
๐ก 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"; }
}
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"); }
}
โ
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"; }
}
Top comments (0)