koin
koin

Reputation: 203

Design-by-contract finding pre-conditions

I have to create a Calculator in Java, based on this Interface.

public interface CalculatorIF {
    int add(int x, int y);
    int sub(int x, int y);
    int mult(int x, int y);
    //double div(int x, int y);
    //int sqrt(int x);
}

But for every Method, I need pre-post conditions. I really need help for pre-conditions, because I can't imagine even a single one which makes sense and isn't already handled by Java.

EDIT: division and sqrt are clear to me, but I need some Ideas for add, sub and mult.

Upvotes: 1

Views: 179

Answers (1)

Alexander Kogtenkov
Alexander Kogtenkov

Reputation: 5790

If you add two Integer.MAX_VALUE values, the result will not fit int and will be truncated. On the other hand, if the input domain is restricted, we can always guarantee that the result is not truncated and has an expected value instead.

For example, if x <= Integer.MAX_VALUE / 2 and y <= Integer.MAX_VALUE / 2, then the sum x + y will be less than or equal to Integer.MAX_VALUE, so there will be no truncation for positive integers. Similar reasoning can be used for negative values and Integer.MIN_VALUE. Preconditions for subtraction can be done the same way.

For multiplication, if either operand absolute value is less than sqrt (Integer.MAX_VALUE), their product will be inside the range of int.

More sophisticated ways to detect overflow and underflow are possible, but for a class exercise such preconditions seem to be fine.

Upvotes: 1

Related Questions