top of page
  • Writer's pictureCristian Duque

The Liskov Substitution Principle (SOLID)

Updated: Nov 6, 2023


The Liskov Substitution Principle (LSP) is one of the SOLID principles used in Object-Oriented Programming. It was introduced by Barbara Liskov in 1987.


In simple terms, LSP states, "Subtypes must be substitutable for their base types." This means that derived classes must behave in the same way as their superclass.


"The LSP applies when there’s a supertype-subtype inheritance relationship by extending a class or implementing an interface. We can think of the methods defined in the supertype as defining a contract. Every subtype is expected to stick to this contract. If a subclass does not adhere to the superclass’s contract, it’s violating the LSP."



LSP is closely related to two OOP pillars: Inheritance and Polymorphism. The IS-A relationship between objects doesn't guarantee to comply with this SOLID principle. We must ensure that all objects from subtypes can be replaced by their superclass without breaking the current application. They don't need to enforce new rules to obtain an expected outcome.



Violations of LSP can be detected as follows:

  • Type checking with IS or AS to identify and manipulate subtypes from the same parent class.

  • Null checks to hide side effects caused by unexpected behaviours or empty logic.

  • NotImplementException statements indicate that subclasses are partially supported by their base classes.


The violation of LSP breaks other SOLID principles. Derivatives are modified whenever they are substitutable for the base class, violating the Open-Closed principle. The Interface Segregation Principle is also violated because subtypes can be forced to implement unused superclass behaviours.



Benefits

  • Reusability and extensibility of one or multiple subtypes from their base code.

  • Less likely to introduce bugs or unexpected situations by ensuring all subtypes can swap from their base class without breaking changes.

  • Flexibility and Scalability in the system by adding new features without touching the actual code.

Drawbacks

  • LSP Misunderstanding can lead to violations and increasing bugs in the system.

  • Complexity by managing structures with several interfaces and classes.


Check out my video:




11 views

Recent Posts

See All

Commentaires


bottom of page