Search code examples
javaoopdesign-by-contractpreconditionspost-conditions

Strengthening and Weakening of pre and post conditions


I have been reading into the topic of Design By Contract and so far have the following notes written:

When strengthening a condition, it means to make it 
more restrictive and weakening a condition is the opposite. 

A subclass' pre-condition is either weaker or the same as its super class'
A subclass' post-condition is either stronger or the same as its super class'

I would like to confirm an example to clarify my understanding.

class exampleA {
    int processInt(int exampleInt) {
        return exampleInt;
    }
}

class exampleB extends exampleA {
    int processInt(int exampleInt) {
        return exampleInt;
    }
}

Design by Contract says if the precondition for processInt in exampleA is, "exampleInt must be greater than 10," and the postcondition is, "the returned value is between 20 and 50," then the precondition of exampleB's method exampleInt must either be the same or weaker, and the postcondition would be the same or stronger.

This means valid preconditions for exampleB could be,

  • Greater than 0
  • Greater than or equal to 0
  • Greater than -100

But invalid preconditions would be,

  • Greater than 20
  • In the range of 20 to 500

Likewise, valid postconditions could be,

  • Between 25 and 45
  • Between 30 and 40

But invalid postconditions would be,

  • Between 20 and 90
  • Between 0 and 50
  • Greater than 0

Is this a correct interpretation of Design by Contract? Also, I am learning this in Java, but I assume the concept applies to any language with OOP?


Solution

  • Yes, your examples are correct; and yes, the same concepts apply to any language that supports polymorphism. Note that Design by Contract is also a part of the Liskov Substitution Principle, which prescribes even more restrictions on subtypes.