π‘ What is Liskov Substitution Principle?
π‘ The Liskov Substitution Principle (LSP), another key part of the SOLID principles, states that:
"Objects of a superclass should be replaceable with objects of its subclasses without affecting the correctness of the program."
In simple terms, if your code functions with a parent class, it should also work seamlessly with any subclass.
π― Simple Example
Imagine a document editing software where users can work with different types of documents. If a user switches from a text document to a spreadsheet, they should still be able to save and print the document without learning new processes. If the spreadsheet removes the ability to save or print, the substitution breaks the system.
π‘ Benefits
β
Improved Reusability: Subclasses can replace parent classes seamlessly, making the code more adaptable.
β
Easier Maintenance: Predictable behavior makes modifying and extending the system simpler.
β
Greater Flexibility: New subclasses can be added without disrupting the system, supporting scalability."
π¨ Violations of LSP
β οΈ Unexpected Behavior: Substituting a subclass causes errors. For example, replacing a smartphone with one that lacks basic calling functionality.
β οΈ Method Restrictions: A subclass limits inherited functionality. For instance, a user account class that removes the ability to reset passwords when the base class allows it.
β οΈ Behavioral Inconsistency: A subclass behaves differently from the superclass. For example, a bird subclass (Penguin) that doesnβt fly while the base class expects flying.
π Applying LSP
π Ensure subclasses maintain the behavior expected by the superclass. For example, all vehicles should be able to start and stop, regardless of type.
π Donβt modify or reduce the functionality of inherited methods. Instead, build upon them to add new capabilities when needed.
π Use abstraction to separate behaviors that may not apply to all subclasses, ensuring consistency and flexibility.
π° Others
Interested? π Check out other posts from my programming principles series!
- KISS Design Principle Explained in 100 Seconds
- DRY Principle Explained in 100 Seconds
- "Tell, Don't Ask" Principle Explained in 100 Seconds
Follow me to stay updated with my future posts:
Top comments (0)