Introduction
In OOP (Object Oriented Programming) languages the solid principle plays a desired design role to make a class flexible and easy to understand. Today we will see the Interface segregation principle.
Why ISP?
When we design/develop a class, that class should not implement any such function which is not required by the customer even those related classes that we are designing or developing.
Let us see with an example of developing a calculator for school, shops, and for programmers.
When we say calculator many things will come into your mind i.e. addition, subtraction, division, multiplication, Trigonometry functions, Calculus etc.
Below is the code which fulfills the requirement of all 3 kinds of users mentioned above.
But if we observe the above code we can understand that we are giving some extra features which users may not interested in (asin, the user won’t use it). For example, a shop holder need only common functions like add, sub, mult, div. this user doesn’t need Trigonometry functions and HexToBinary and vice versa functions.
And school students need Common functions + Trigonometry functions + may need or may not need HexToBinary and Vice versa function.
But as we designed and developed classes including all together we don’t have an option for segregation here. We need to deliver all features to the end-user.
At this stage our ISP will play key role. We can split Calculator class into the below interface (Contracts).
-
-
-
- public interface ICommonCalci {
- int add(int[] nums);
- int substract(int a, int b);
- int multplicaton(int[] nums);
- int division(int a, int b);
- }
-
-
-
- public interface IProgrammerCalci {
- String convertHexToBinary(String input);
- String convertBinaryToHex(String input);
- }
-
-
-
- public interface ITrigonometryCalci {
- double sinOf(double x);
- double cosOf(double x);
- double tanOf(double x);
- }
And below is the newly designed calculator class by inheriting all 3 interfaces. Based on user needs we can deliver the particular interface(s) to the user.
As per the above code, we can see that,
- For Shop holders we can provide interface ICommonCalci
- For Programmers we can provide ICommonCalci + IProgrammerCalci.
- For Students we can provide ICommonCalci + ITrigonometryCalci + IProgrammerCalci (Based on Requirement)
This way we fulfilled all user requirements. And still this class is feasible to extend with new interfaces for new kinds of users and for new kinds of requirements.
Summary
In this article we learned about the interface segregation principle. I attached source code for this article. Download and extend it for better understanding.