Activity 4.7 - Defensive programming

Topic

In this activity we explore the use of defensive programming techniques 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 FixedSizeQueue class supplied does not have any protection against an attempt to add an item when the queue is already full. At this stage, it also will not compile.

Instructions

  1. In the class FixedSizeQueue complete the helper method isFull and modify the add method, so as to prevent an attempt to add an item when the queue is full. You should not need to change the test program in class Main.

    When you have made these changes, run the project. You should get a message, indicating that the attempt to add too many items has been prevented.

  2. Now remove the changes to the add method (commenting them out may be the best approach) but leave the code you added to the isFull method. Run the project again. What happens this time?