Article
Liskov Substitution Principle: Trust Your Abstractions
Subtypes must be substitutable for their base types. Don't break the promise of your interfaces.
The Liskov Substitution Principle (LSP) ensures that a subclass can stand in for its parent class without breaking the application logic.
The Famous Square/Rectangle Problem
If a Square inherits from a Rectangle, and setting the width of the Rectangle also changes its height (to keep it square), it breaks the expectations of any code that thinks it's working with a normal Rectangle. This is a classic LSP violation.
Why LSP Matters
LSP allows you to use polymorphism safely. When you adhere to LSP, you can pass any subclass to a function expecting a base type, and that function will continue to work correctly without needing to know the specific type.
Breaking LSP leads to 'type checks' (e.g., instanceof) scattered throughout your codebase, which is a major red flag for poor design.
Recommended by our partners
Discussion
Keep the conversation going
Log in to join the discussion.
No comments yet. The first thoughtful reply can set the tone for the whole thread.