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)