Incremental Java
Adding Conditional Statements to a Class

Error Checking

When we wrote the class definition for Rectangle, we assumed the object user would pass in reasonable values for height and width. In particular, we assumed that the values would be non-negative. There's no check to see what happens if the value is negative.

We do allow rectangles that have zero width or zero height or both.

We needed conditional statements before we could check for errors. In general, error checking looks like:

if ( error )
  // Handle error
We can check for errors in the constructor and the setWidth(), setHeight() methods.

Rewriting Rectangle

public class Rectangle
{
   private int width = 0, height = 0 ;

   public Rectangle()
   {
   }

   public Rectangle( int initWidth, int initHeight )
   {
      if ( validSize( initWidth ) && validSize( initHeight ) )
      {
         width = initWidth ;
         height = initHeight ;
      }
   }

   public int getHeight()
   {
      return height ;
   }

   public int getWidth()
   {
      return width ;
   }

   public void setHeight( int newHeight )
   {
      if ( validSize( newHeight ) )
      {
         height = newHeight ;
      }     
   }

   public void setWidth( int newWidth )
   {
      if ( validSize( newWidth ) )
      {
         width = newWidth ;
      }     
   }

   public int getArea()
   {
       return width * height ;
   }

   public int getPerimeter()
   {
       return 2 * ( width + height ) ;
   }

   // Private method
   private boolean validSize( int size )
   {
       return size >= 0 ;
   }
}
We added a validSize() method to check to see if the size is valid. If it isn't then no changes are made. Normally, we have to be careful with the constructor. If the object user calls the constructor with the incorrect values, we still need to initialize height and width. Fortunately, we wrote intializers for those instance variables and set them to 0.