Photo by Pavel Nekoranec on Unsplash
This is a continuation of the SOLID. In the last post, I covered the L and now we will be continuing with the L. So if you didn't check the last post, feel free to click on the link: https://dev.to/sightlessdog/revisiting-the-l-in-solid-116m
Interface Segregation Principle
The Interface Segregation Principle was defined by Robert C. Martin several years ago while consulting for Xerox. He helped them change their printing system which was difficult to develop.
He defines it as :
No client should be forced to depend on methods it does not use.
In other words, Changing one method in a class shouldn't affect classes that don't depend on it.
Or we can say larger interfaces should be split into smaller ones.
Example:
Let's suppose 10 people work at a restaurant, our restaurantWorker class would look like this.
public interface RestaurantWorker {
void washDishes();
void cook();
void serve();
}
Out of the 10 people, there is this guy who doesn't know how to cook (he can only wash dishes or serve). Then the method cook() is not really relevant to him.
But sadly we have to implement the method cook() right?
To fix this, we would have to separate our interface into smaller ones
public interface Waiter {
void serve();
}
public interface Cook {
void cook();
}
public interface DishWasher {
void washDishes();
}
public class theGuyNoCook implements DishWasher, Waiter {
public void washDishes() {
}
public void serve() {
}
}
And now, we are free to implement only the relevant methods.
Conclusion:
The ISP is intended to keep away the strong coupling between the different parts of the system. And that's what makes the code we are writing easier to change, refactor and redeploy.
Sources:
https://en.wikipedia.org/wiki/Interface_segregation_principle
Robert C. Martin “Principles of OOD”
Meyer, B. (1997): Object-Oriented Software Construction, 2nd edition
http://www.cvc.uab.es/shared/teach/a21291/temes/object_oriented_design/materials_adicionals/principles_and_patterns.pdf
Top comments (0)