Friday, May 20, 2011

Liskov's Substitution Principle(LSP)

The Liskov’s Substitution Principle provides a guideline to sub-typing any existing type. It is L in SOLID principles.

 If for each object o1 of type S there is an object o2 of type T such that for all programs P defined in terms of T, the behaviour of P is unchanged when o1 is substituted for o2 then S is a subtype of T.

Here is an easier version:
Functions or methods that use pointers or references to base classes must be able to use objects of derived classes without knowing it.
While checking for specific types is technically a violation of LSP, it's more commonly thought of as an OCP violation. LSP is more focused on the behavior of the specific instance itself, rather than types operating upon the specific instance. Below is an example of some code breaking this principle:

Violation of LSP - Consider the case of Rectangle and Square problem.

Right way to handle solve this problem - Solution to rectangle square problem.

This principle is just an extension of the Open Close Principle and it means that we must make sure that new derived classes are extending the base classes without changing their behavior.

No comments:

Post a Comment