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:
- FixedSizeQueue, which is an incomplete, 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 defensive programming techniques
we are interested in here.
- Main, which, as usual, contains test code.
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
- 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.
- 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?