In Eiffel it is said that we should "loosen the pre-conditions and tightening the post-conditions", but I am not sure what this means. How does this benefit/is benefited by sub-classing?
Thank you
In Eiffel it is said that we should "loosen the pre-conditions and tightening the post-conditions", but I am not sure what this means. How does this benefit/is benefited by sub-classing?
Thank you
In Design by Contract, you specify a set of pre-conditions and a set of post-conditions for a function. For example, let's say you were writing a memory allocation function. You require that it accept a positive integer as input, and produces an evenly aligned pointer as its result.
Loosening the precondition means that when you create a derived class, it has to accept any input that the base class could accept, but might accept other inputs as well. Using the example above, a derived class could be written to accept a non-negative integer instead of just positive integers.
On the result side, you have to ensure that the result from a derived function meets all the requirements placed on the base function -- but it can also add more restrictions. For example, a derived version of the function above could decide to only produce results that were multiples of 8. Every multiple of 8 is clearly even, so it still meets the requirement of the base function, but has imposed an additional restriction as well.
The opposite would not work: if the base class function allows non-negative integers as input, then the derived class must continue to accept all non-negative integers as input. Attempting to change it to accept only positive integers (i.e., reject 0, which is allowed by the base class) would not be allowed -- your derived class can no longer be substituted for the base version under all circumstances.
Likewise with results: if the base class imposed a "multiple of 8" requirement on a result, the derived version must also ensure that all results are multiples of 8. Returning 2 or 4 would violate that requirement.