Liskov Substitution Principle can be stated as: A type must be substitutable by its subtypes without altering the correctness of the application.
To make it easier let's start with an example. See the image below:
As you can see there is an interface IAnimal that defines two methods, speak() and sleep(). The IAnimal interface is implemented by two classes Parrot and Elephant. So far, so good but let's say that we should include ants in the application. To incorporate this change create an additional class called Ant that implements IAnimal. Since ants do not speak once you implement the interface the code would look something like this:
@Override
public void speak() {
throw new UnsupportedOperationException("Not supported yet.");
}
Now we can see a problem that might cause errors in the application. To correct this you can split the IAnimal interface into two. IAnimalSpeak and IAnimalSleep. The modified design is shown below.
To begin with, this example lets create the two interfaces, IAnimalSpeak and IAnimalSleep including the corresponding methods.
Reference
Joshi, B. (2016b). Beginning SOLID Principles and Design Patterns for ASP.NET Developers (English Edition) (1st ed.). Apress.
Comments
Post a Comment