8 ● ASSERTIONSASSERTIONS ARE STATEMENTS WRITTEN INTO SOFTWARE THAT...

17.8

Assertions

Assertions are statements written into software that say what should be true of the data.

Assertions have been used since the early days of programming as an aid to verifying the

correctness of software. An assertion states what should always be true at a particular

point in a program. Assertions are usually placed:

at the entry to a method – called a precondition, it states what the relationship

between the parameters should be

at the end of a method – called a postcondition, it states what the relationship

within a loop – called a loop invariant, it states what is always true, before and after

each loop iteration, however many iterations the loop has performed.

at the head of a class – called a class invariant, it states what is always true before

and after a call on any of the class’s public methods. The assertion states a relation-

ship between the variables of an instance of the class.

An example should help see how assertions can be used. Take the example of a class

that implements a data structure called a stack. Items can be placed in the data struc-

ture by calling the public method

push

and removed by calling

pop

. Let us assume that

the stack has a fixed length, described by a variable called

capacity

. Suppose the class

uses a variable called

count

to record how many items are currently in the stack. Then

we can make the following assertions at the level of the class. These class invariant is:

assert count >= 0;

assert capacity >= count;

These are statements which must always be true for the entire class, before or after

any use is made of the class. We can also make assertions for the individual methods.

Thus for method

push

, we can say as a postcondition:

assert newCount = oldCount + 1;

For the method

push

, we can also state the following precondition:

assert oldCount < capacity;

SELF-TEST QUESTION