The Interface Segregation Principle
The Interface Segregation Principle
Today we are taking a look at the fourth of the SOLID Principles; The Interface Segregation Principle (ISP).
Imagine we have a DataAccess class for saving data to, and retrieving data from, a database. We also have three high-level business logic classes, UseCase1, UseCase2 and UseCase3. The use cases call methods on DataAccess. Each of the use cases calls a different set of methods on DataAccess to store and get data.
What if UseCase1 required a new method on DataAccess? UseCase2 and UseCase3 will not be calling this method. In a statically-typed language like C#, DataAccess has changed, and we must recompile it. Since UseCase1 is calling the new method on DataAccess, it will also require recompilation. So far, so good.
Now, UseCase2 and UseCase3 are not interested in the recent change in DataAccess. However, since they are dependent on DataAccess, both UseCase2 and UseCase3 require recompilation. Armed with our modern IDEs that is not usually a problem – these tools will detect classes that need rebuilding and do so quickly and efficiently.
But it gets worse. If each of these four classes lives in a different component, the smallest unit of deployment, then we will need to redeploy all four components – even the ones containing UseCase2 and UseCase3! Instead of getting away with deploying only 2 DLLs (DataAccess & UseCase1), we are now looking at having to deploy all four DLLs, or we risk failures at runtime.
Static vs Dynamic Typing
In this regard, ISP is only a problem for statically-typed languages like C# and Java. In these languages, we create fixed source code dependencies via include, import and using statements.
JavaScript and Python are dynamically-typed languages, and they do not have this problem. Dynamically-typed languages interpret source code dependencies at runtime.
OK, back to our problem re changes in DataAccess forcing recompilation and redeployment in UseCase2 & UseCase3.
So, what is the solution?
Generally, avoid depending on things you don’t need. Need as little as possible. Depending on more than required may mean being buffeted by modifications to code you’re not calling.
When we do have a class like DataAccess that is used by multiple clients, there is a technique we can use to isolate the clients from changes in DataAccess. More on that tomorrow.
Leave a Reply
Want to join the discussion?Feel free to contribute!