zzoorrii
zzoorrii

Reputation: 11

What can happen in a program where a subclass strengthens preconditions in a overriden method?

I'm puzzling around this question. I would be happy to know which is the correct answer and why?

Liskov Substitution Principle states that it is allowed to weaken preconditions in overriden methods. What can happen in a program where a subclass strengthens preconditions in a overriden method?

  1. The code after a call to the overriden method might break because it makes assumptions on the return value from the overriden method.
  2. It might be not possible to invoke the overriden method since the code assumes weaker preconditions.
  3. Nothing will happen - the code will always run correctly as before.
  4. If the code is written in Java it might not compile.

Thanks in advice!

Upvotes: 0

Views: 98

Answers (2)

reaanb
reaanb

Reputation: 10064

A strengthened precondition sets a tighter bound on the possible values that can be passed to the method. In other words, the domain of the overridden method is a subset of the domain of the base class's method. Therefore:

  1. If the strengthened precondition doesn't fail (i.e. if the calling code passed a value in the subset accepted by the strengthened precondition), then the method would return the same result as it would've for the base class's method (as required by the LSP). Therefore, the calling code can't break after the call.

  2. This is the correct answer. Consider a method defined for any integers, which is overridden to accept only positive integers. The calling could would not be aware of the strengthened precondition since it's accessing the subclass polymorphically, and if it passed a negative integer (which was valid previously), the call would fail for the overridden method of the subclass.

  3. This may be the case but isn't necessarily true.

  4. This may be the case but isn't necessarily true.

For further reading, see Wikipedia: Covariance and contravariance - Covariant method argument type

Upvotes: 0

Jorge.V
Jorge.V

Reputation: 1347

I'd go with:

  1. Is true, because the preconditions affecting the parameters can affect the return value. Take for example a mathematical function that can only take positive numbers and gives unexpected results with others.
  2. Is false, if the method is overriden it takes the same parameter types and has the same return type and can be invoked.
  3. Is not necesarily true and hence false because of 1.
  4. Is false for the same reason 2. is false.

Upvotes: 2

Related Questions