DEV Community

Dzung Nguyen
Dzung Nguyen

Posted on

Liskov Substitution Principle (LSP) Explained in 100 Seconds

πŸ’‘ 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.

LSP 1

LSP 2

πŸ’‘ 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!


Follow me to stay updated with my future posts:

Top comments (0)