Assertions, Pre/post-Conditions and Invariants: Programming As A Contract
Assertions, Pre/post-Conditions and Invariants: Programming As A Contract
Programming as a contract
Precondition
What is assumed to be true before the method is
executed
Caller obligation
Postcondition
q
Example
Enforcing preconditions
/*
** precondition: x >= 0
** postcondition: return value satisfies:
** result * result == x
*/
double sqrt(double x) {
/*
** precondition: x >= 0
** postcondition: return value satisfies:
** result * result == x
*/
double sqrt(double x) {
if (x < 0)
throw new ArithmeticExpression (you
tried to take sqrt of a neg number!);
Class Invariants
n
What is an assertion?
n
2/14/13
What is an assertion?
n
assert
Using assert:
assert n
while (n
n = 2
}
assert n
//n == 1
while (n < limit) {
n = 2 * n;
}
//n >= limit
Another example
== 1;
< limit) {
* n;
>= limit;
if (i % 3 == 0) { ... }
else if (i % 3 == 1) { ... }
else { // We know (i % 3 == 2)
... }
if (i % 3 == 0) { ... }
else if (i % 3 == 1) { ... }
else { assert i % 3 == 2; ... }
Another example
Another example
int p=,d=;
int q = p/d;
int r = p%d;
assert ?
int p=,d=;
int q = p/d;
int r = p%d;
assert p == q*d + r;
2/14/13
Control Flow
n
Programming by contract
Preconditions in methods (eg value ranges
of parameters) should be enforced rather
than asserted because assertions can be
turned off
Postconditions
q
Assert post-condition
Assertions
n
Syntax:
assert Boolean_Expression;
Performance
n
n
n
n
n
n
Assertions in Eclipse
n
More Information
n
2/14/13
Loop invariants
n
Loop invariants
<precondition: n>0>
int i = 0;
while (i < n){
i = i+1;
}
<post condition: i==n >
We want to prove:
i==n right after the loop
2/14/13
. . . . . . .!
5
4
3
2
1
.
.
.
.
.
1
.
.
.
.
.
2
.
.
.
.
.
3
.
.
.
.
.
4
.
.
.
.
.
5
.
.
.
.
.
6
.!
.!
.!
.!
.!
7!
!
Question: Does either Red or Blue have a winning
strategy?!
See http://www.cs.uofs.edu/~mccloske/courses/cmps144/invariants_lec.html
if (j>1) {!
draw a horizontal line segment connecting (i+1,j-1) with (i+1,j)!
} else {!
draw a line segment anywhere!
}!
}!
*2
*2
*2
*2
2/14/13
Try it on 7 * 8
left
7
right a
8 7
3
1
0
Try it on 8*7
b
8
16
32
64
p
0
+=b: 8
+=b: 24
+=b: 56
5
10
left right a
8
7 8
4
2
1
0
b
7
14
28
56
118
p
0
0
0
0
+=b: 56
80
95