The Interface Segregation Principle states the following: Clients of a class should not be forced to depend on those of its methods they don't use.
Suppose you are building an animal simulator and you design an interface as shown below.
In the beginning, you think that the application will accept only animals. So you design the IBehaviour interface to have three methods. eat(), sleep(), move(). Now let's assume that the application would not simulate animals, it would also simulate plants. The solution sounds quite simple, you just create the Plant class and implement the IBehaviour interface. But there is a problem a plant can't move and also can't sleep, so the methods sleep() and move() would end up having nothing inside as shown below.
@Override
public void move() {
throw new UnsupportedOperationException("Not supported");
}
@Override
public void sleep() {
throw new UnsupportedOperationException("Not supported");
}
At this stage, your code may work as expected, but a potential problem may arise in the future. So how do we solve this problem? Let's split the required operations into three interfaces as shown below.
To begin developing this example create three interfaces IEat, ISleep, IMove.
public interface IEat {
public void eat();
}
public interface ISleep {
public void sleep();
}
public interface IMove {
public void move();
}
Then create the classes Plant and Animal implementing the corresponding interfaces.
public class Animal implements IEat, IMove, ISleep{
@Override
public void eat() {
System.out.println("Aniaml eating...");
}
@Override
public void move() {
System.out.println("Animal moving...");
}
@Override
public void sleep() {
System.out.println("Animal sleeping...");
}
}
public class Plant implements IEat{
@Override
public void eat() {
System.out.println("Plant eating...");
}
}
As you can see the class Animal implemented the interfaces IEat, IMove, and ISleep and has the methods eat(), sleep(), and move(). Besides the class Plant only implementer the interface IEat and has the method eat().
Reference
Joshi, B. (2016b). Beginning SOLID Principles and Design Patterns for ASP.NET Developers (English Edition) (1st ed.). Apress.
Comments
Post a Comment