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:

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

  1. As a first step, run the project without making any changes. You should see what happens when the contract is broken.
  2. 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.