Discussion of Activity 4.7 - Defensive programming

Here is our sample solution for the FixedSizeQueue class:

public class FixedSizeQueue
{
   private int maxItems;       // maximum number of items in the queue
   private int numberOfItems;  // current number of items in the queue
   private int[] queue;        // the queue items

   // Constructor - create a queue of specified capacity
   public FixedSizeQueue(int capacity)
   {
      maxItems = capacity;
      numberOfItems = 0;
      queue = new int[capacity];
   }

   // add a new item to the end of the queue
   // ** modify this method to protect against adding too many items
   public boolean add(int newItem)
   {
      if (isFull())
      {
         return false;
      }
      else
      {
         queue[numberOfItems] = newItem;
         numberOfItems++;
         return true;
      }
   }

   // returns true if the number of items in the queue is at its maximum
   private boolean isFull()
   {
      return(numberOfItems >= maxItems);
   }

   // return contents of queue in string format
   public String toString()
   {
      String queueString = "";
      for (int i = 0; i < numberOfItems; i++)
      {
         queueString += (queue[i] + " ");
      }
      return queueString;
   }
}

Notes

Initially the unchanged program should not compile.

  1. After the required modifications, shown above, it should run to completion.
  2. When the modifications to the add method are removed, an exception should occur.  This shows that programs that are not carefully checked and made robust may result in a RunTimeException.