Activity 4.8 - Designing by contract
Topic
In this activity we explore the use of design by contract as a way of
preventing run-time exceptions.
Materials
In addition to the Solution document, the project
for this activity contains two classes:
- FixedSizeContractQueue,which is a partial implementation of a very simple
queue of integers. It is a partial implementation because it only permits items
to be added to the queue, not removed. This is not very practical but is enough
to demonstrate the design by contract technique we are interested in here.
- Main, which, as usual, contains test code.
Task
The FixedSizeContractQueue class supplied does not have any protection
against an attempt to add an item when the queue is already full. It does
however have a contract defined by the pre-condition of the add method - this
method only guarantees to add an item to the end of the queue if the queue is
not full. See the comments preceding the code for this method. You should not
need to change any code in this class.
Instructions
- As a first step, run the project without making any changes. You should
see what happens when the contract is broken.
- Now modify the test code in the main method of the class Main so as to
ensure that the contract for the add method holds i.e.
you should prevent any attempt to add an item when the queue is full.
When you have made the required changes, run the project. You should get a message
indicating that the attempt to add too many items has been prevented.