Liskov Substitution – How Strengthening Preconditions and Weakening Postconditions Violate Liskov Substitution Principle

abstractioninheritanceliskov-substitutionobject-oriented

I read that Liskov's substitution principle is violated if :

  1. Preconditions are strengthened, or

  2. Postconditions are weakened

But I don't get fully yet how these two points would violate Liskov substitution principle. Can some one please explain with an example. Specifically, how would any one of the above conditions cause a situation where a subclass object can not be substituted for a superclass object?

Best Answer

  1. Assume your baseclass works with a member int. Now your subtype requires that int to be positive. This is strengthened pre-conditions, and now any code that worked perfectly fine before with negative ints is broken.

  2. Likewise, assume the same scenario, but the base class used to guarantee that the member would be positive after being called. Then the subtype changes the behavior to allow negative ints. Code that works on the object (and assumes that the post-condition is a positive int) is now broken since the post-condition is not upheld.

These are of course trivial examples, but the concept holds. Stuff like leaving a file/database connection open is an example of an eased post-condition that leads to issues.

Related Topic