The Liskov Substitution principle

The Liskov Substitution principle may be difficult to understand at first due to its somewhat complex and mathematical definition. From Barbara Liskov's Data Abstraction and Hierarchy [https://pdfs.semanticscholar.org/36be/babeb72287ad9490e1ebab84e7225ad6a9e5.pdf], the principle is stated as follows:

What is wanted here is something like the following substitution property. 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 behavior of P is unchanged when o1 is substituted for o2, then S is a subtype of T.

Uncle Bob has simplified this definition to be, Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it. Looking at this principle, it seems like it would just be inheritance. Except, it's not just inheritance. This principle implies that not only does the object replacing the other have to implement the same interface or contract as the original, it must also adhere to the same expectations as the original.

The classic example of a violation of this principle is the use of a square class in the place of a rectangle class. A typical rectangle class would need to have both length and width properties. In mathematics, a square is just a special type of rectangle. So, many would assume that creating a square class with length and width would be an acceptable swap for the rectangle class.

The problem here is that a square requires that both length and width have the same value. So, when you change either one on the square class, the class will update the other to have the same value. This is a problem because the application using the object doesn't expect this behavior. Therefore, the application must be aware of the possibility of the length or width changing without notice.

A failure to meet the expectations of the application is known as a refused bequest. A refused bequest can cause inconsistent behavior in an application and, at the very least, requires more code to compensate for the mismatch.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.211.189