The Interface Segregation Principle (ISP) states that a class should not be forced to depend on interfaces that it does not use. In other words, it's better to have several specific, cohesive interfaces than a single large, generic interface. This prevents classes from implementing methods that are not relevant to them, reducing complexity and improving code maintainability.
Example Before Applying ISP in PHP:
Consider an example where we have a Worker
interface that represents workers in an office. They can work, take vacations and also have fun in social activities.
interface Worker {
public function work();
public function takeHolidays();
public function socialActivities();
}
However, by implementing this interface across different classes, we could end up with methods that are irrelevant for certain types of workers. For example, for an Intern
, the takeHolidays()
method may not be applicable, but the interface forces you to implement it.
Example After Applying the ISP in PHP:
To apply the ISP, we can divide the Worker interface into smaller, more specific interfaces, according to the expected behavior for different types of workers.
interface Worker {
public function work();
}
interface EmployeeWithHolidays {
public function takeHolidays();
}
interface SocialWorker {
public function socialActivities();
}
Now classes representing different types of workers can implement only the interfaces relevant to them:
<?php
class Employee implements Worker, EmployeeWithHolidays {
public function work() {
// specific implementation to work with
}
public function takeHolidays() {
// specific implementation for taking vacation
}
}
class Intern implements Worker {
public function work() {
// specific implementation to work with
}
}
In this example, the Employee
class implements the Worker
and EmployeeWithHoliday
interfaces, as it is a regular worker who also takes vacation. The Intern
class only implements the Worker interface, as it does not need the takeHolidays()
method. In this way, we are following the ISP, ensuring that classes are not forced to implement methods that are not relevant to them, making the code more cohesive and easier to maintain.
Thanks for reading!
If you have any questions, complaints or tips, you can leave them here in the comments. I will be happy to answer!
๐๐ See you later! ๐๐
Support Me
Youtube - WalterNascimentoBarroso
Github - WalterNascimentoBarroso
Codepen - WalterNascimentoBarroso
Top comments (0)