Interface Segregation Principle in real-life example
Most of you have read a dozen times probably what‘s this principle about. Vehicles, bikes, ducks. Let’s see a real-life explanation instead.
No theoretical nonsense today. We jump straight into business. Are you using interfaces? If not, this publication won’t bring you any value.
The only quote you should remember is the following one by Uncle Bob:
Keep interfaces small so that users don’t end up
depending on things they don’t need
This is a typical User Repository before applying the ISP principle:
Now you end up injecting this interface across entire application. When building a functionality that lists all the application’s users, do we need the persistence-related methods? And vice-versa, if creating a new user, do we need all the finder methods?
We can improve this interface by applying the ISP principle. We can easily spot at least two categories of methods in this case: persistence related (add, remove) and finder methods (the other ones).
Let’s split the interface into two:
Pros of splitting the interface:
- you can have different implementations for each interface
- implementations are leaner
- improved code quality
Nothing can stop you from having a single implementation if you wish:
Any doubts? Thoughts? Please leave me a comment on what you think. Let’s together make our code beautiful. Subscribe to my publications for more articles like this to become a better developer.
Was this story of any value to you? Please support my work by leaving a 👏 clap as a token of appreciation. Did you know that you can clap more than once? 🥰 Thank You.