Week 13-DIP & ISP
Week 13-DIP & ISP
Week 13-DIP & ISP
&
Interface Segregation Principle
The DIP principle states that:
Therefore, we introduce an
abstraction.
The BackEndDeveloper shall be refactored to:
And the FrontEndDeveloper shall be refactored to:
The next step, in order to tackle the violation of the first part, would be to refactor the Project
class so that it will not depend on the FrontEndDeveloper and the BackendDeveloper classes.
Conclusion:
The outcome is that the Project class does not depend on
lower-level modules (FrontEndDeveloper and the
BackendDeveloper classes), but rather abstractions (interface
Developer).
Also, low-level modules and their details depend on
abstractions.
Example
You all must have played one of the popular games, Subway Surfers. There are different tour themes to choose from like
World Tours (New York City, Paris etc.), Film Tours (Madagascar, Despicable Me etc.). Now consider the following code:
And our Game class uses both in order to display all the available tour themes.
Example:
Consider a large interface that is not cohesive and clients are forced to implement all
methods:
Refactoring with ISP:
interface Worker {
void work(); interface Workable {
void eat(); void work();
void takeBreak(); }
}
interface Eatable {
class Engineer implements Worker { void eat();
public void work() { }
// Code for working
} class Engineer implements Workable, Eatable {
public void work() {
public void eat() { // Code for working
// Code for eating }
}
public void eat() {
public void takeBreak() { // Code for eating
// Code for taking a break }
} // No longer forced to implement unnecessary methods
} }
The ISP helps in creating smaller and more focused interfaces, allowing clients to implement only the methods
they need, thus reducing unnecessary dependencies.
ISP CONTD…
Without ISP:
• In absence of ISP, you have one Generic large interface and many
classes implementing it.
• Assume that you had 1 interface and 50 classes. If there is a change in
interface, all 50 classes have to change their implementation
WITH ISP:
• You will divide generic interface into small interfaces.
• If there is a change in small interface, only the classes implementing
that interface will be affected.
• To make the code more readable and manageable.
EXAMPLE- VIOLATING ISP
SOLUTION