Abstraction is the most essential piece of object-oriented design. It allows the client peace of mind when it comes to the implementation details of functionality. In Java, abstraction is achieved through abstract classes and interfaces. This post will find the idea of the Interface Segregation Principle.
An Interface is a set of abstractions that an implementing class must follow. We define the behavior but don’t implement it:
in the example below, we will find how that is being written.
interface Car {
void break();
}
Using the interface as a template that actually can help us to implement the behavior:
class Toyota implements Car {
public void break(){
// Toyota-specific implementation
}
}
What Is the Interface Segregation Principle?
The Interface Segregation Principle (ISP) states that a client should not be exposed to methods it doesn’t need. Declaring methods in an interface that the client doesn’t need is problematic for several reasons.
Let’s look at an example to understand why the Interface Segregation Principle is helpful.
By creating these codes below you will be able to analyze how the methods are being called. Let’s formed an order service place where a customer can order an oil change, change tires, or basic tuneup:
interface OrderService {
void oilchange(int quantity);
void tirerotation(string front, string back);
void basictuneup(int quantity, string front, string back);
}
Since a customer has the opportunity to order an oil change, or tire rotation, or both, it will make sense to put all order methods in a single interface which be seen in the codes below.
class OilchangeOrderService implements OrderService {
@Override
public void oil-change(int quantity) {
System.out.println(“Received order of “+quantity+” oil change”);
}
@Override
public void ordertireroation(string front, string back) {
throw new UnsupportedOperationException(“No tirerotation in oil change only order”);
}
@Override
public void ordertuneup(int quantity, string tireration) {
throw new UnsupportedOperationException(“No tirerotation in oilchange only order”);
}
}
Similarly, for a tirerotation-only order, we’d also need to throw an exception in orderOilchange() method.
And this is not the only downside of this design. The OilchangeOrderService and TirerotationOrderService classes will also have unwanted side effects whenever we make changes to our abstraction.
This change will also affect oilchangeOrderService even though it’s not implementing this method!
By violating the ISP, we face the following problems in our code:
• Client developers are confused by the methods they don’t need.
• Maintenance becomes harder because of side effects: a change in an interface forces us to change classes that don’t implement the interface.
From the blog CS@Worcester – Site Title by proctech21 and used with permission of the author. All other rights reserved by the author.