SOLID Class Design: The Liskov Substitution Principle written by Tom Dalling on Tomdalling.com is a five part series about the SOLID class design principles in OOP. He starts off with a problem about inheritance. For instance, if you had a penguin which is a bird that falls under an “is a” relationship. However, when the penguin inherits from the bird class, it will also inherit the fly method. As soon, as you set the fly function to do nothing, then it violates the LSP. Then Tom explains that from applying the Open Closed Principle, subclasses must follow the interface of the abstract base class. If the class has to be altered in such a way to account for certain classes then it also violates the Open Closed Principle of being able to extend a classes behavior without modifying it. In conclusion, two solutions are presented, one is adding a method to check for a flying bird or non-flying bird. The other which, he states as a better solution, would be to create separate classes to account for a flightless type, that way the fly method is not inherited from the superclass.
After doing assignments for CS-343 revolving around refactoring a pre-existing poorly implemented code by applying design patterns. I did not realize that we touched upon the Liskov Substitution Principle before reading the blog post. However, choosing this post, serves as a great source of review material upon topics covered in class. The assignment that incorporated multiple design patterns started off with a clear application of the LSP, as the original design had two instances of overriding to do nothing. However, the criteria for our first refactor requires the LSP and other inheritance reworks. Since we were working with Ducks, you can imagine a QuackBehavior and a FlyBehavior, that incorporated real and inanimate ducks. So, the LSP application is similar to the second solution presented earlier, in which the fly and quack methods aren’t inherited from a superclass but rather an interface later implemented by the duck class. But even though the method still does nothing, it isn’t an override method, so it does not violate the LSP.
Like other OOP principles, these exist to help achieve code that is maintainable and reusable. By acknowledging the existence of these SOLID class design principles, it will hopefully prevent future projects from projecting these type of code smells. Also, by understanding them and utilizing them wherever they suit best, my code will be cleaner, easier to maintain and add new features.
From the blog CS@Worcester – Progression through Computer Science and Beyond… by Johnny To and used with permission of the author. All other rights reserved by the author.