The actual subtype precondition is created by combining (using logical OR ) the base type preconditions and the subtype preconditions, which makes the resulting precondition less restrictive
The actual postcondition of the subtype is created by combining (using logical AND ) postconditions of the base type and postconditions of the subtype, which makes the resulting postcondition more restrictive
The following are examples of simplifying preconditions and easing postconditions that as a result violate the LSP ( Link ):
Suppose your base class works with an int element. Now your subtype requires int to be positive. This is a reinforcement of preconditions, and now any code that worked fine with negative ints.
Similarly, suppose the same scenario, but the base class, is used to guarantee that the member will be positive after it is called. then the subtype modifies the behavior to allow negative ints. The code that works on the object (and assumes that the post-condition is a positive int) is now violated, since the post-condition is not supported.
a) Why is this also not considered a violation of the LSP when an overridden method relaxes the precondition, since this method may use parameters that are unacceptable for basic contracts. Thus, we cannot claim that the base type contract was violated, and as a result, the LSP was also violated?
b) Why is this also not considered a violation of the LSP when an overridden method reinforces the postcondition, since clients calling this method will receive only a subset of the possible results of the original method. Thus, we cannot claim that the base type contract was violated, and as a result, the LSP was also violated?
Example:
The postcondition of the base class ensures that the return value of the method is within the range of 1-10 , but then the subtype changes the postcondition to allow only the return value in the range of 2-9 . Now the code that works with the object returned using this method (and assumes that post-existence is within the range of 1-10 ) is broken, because the postcondition is not supported.
Edvrusj
source share