📎 Webclip
Liskov Substitution Principle in C# with Example
The page explains the Liskov Substitution Principle as a rule of object-oriented design in which objects should be replaceable with subtype instances without breaking program correctness. It uses a Bird and Ostrich example to show how an overridden Fly method that throws an exception breaks substitution.
Reading notes#
- LSP is presented as one of the five SOLID principles.
- A subtype should be usable wherever the base type is expected without changing the program’s correctness.
- In the first example, Bird defines Fly and Ostrich overrides Fly to throw NotSupportedException.
- Assigning an Ostrich to a Bird reference and calling Fly causes an exception.
- The text treats that exception as a violation of LSP because the derived class changes the expected behavior.
- To follow LSP, the page suggests a better hierarchy or interfaces for different behaviors.
- It introduces IBird with a Move method as the shared contract.
- FlyingBird implements IBird and calls Fly from Move.
- Ostrich implements IBird and calls Run from Move.
- In the refactored code, both FlyingBird and Ostrich can be used through IBird without breaking the program.
- The page concludes that this design makes the code more robust, maintainable, and scalable.
