Checking Class Invariants

You should always try and answer the question "can I feed this method something that will cause the class invariants to be violated?" If I pass in a negative number of sides for shape, will it accept it? If I give my cash register a negative amount of money, what will happen?In the following code for example, the first if condition checks to ensure that the class invariant is maintained. Inside the main method below, a test case is created which tests a case when the class invariant would be not met (by passing a nonpositive value for the number of sides).


public static void main(String[] args) {
  //Test shape
  Shape s = new Shape(-1);
}

public Shape(int numSides) {
   if(numSides < 1) {
      throw new RuntimeException("Number of sides cannot be negative");
   }
...
}

The SearchArray class in its constructor takes in an array and two integers, minVal and maxVal. This class has the following two class invariants:
  1. minValue must always be smaller than or equal to maxVal.
  2. Each element of the array must be greater than or equal to minValue and less than or equal to maxValue
The following code is present in the existing constructor which ensures that the first class invariant is not violated.

//class invariant#1 checking code
if(maxVal < minVal){
	System.out.println("\tClass invariant " +
			"not met: maxVal cannot be less than minVal");
	return;
}

The test case to check this class invariant can be found in the main method
//test case to check class invariant#1
/*
System.out.println("Passing minVal > maxVal. Expecting error statement.");
int[] testArray1={1,2,3,4,5};
s=new SearchArray(testArray1,10,9);
*/
Uncomment the above section and run the code. Note the values passed to the constructor in the code above. The argument minVal is passed as 10 and maxVal as 9, clearly violating the first class invariant. An error message is expected in this test case and you should see an exception thrown in the console. This just tells you that the invariant checking code is in place and working. After you have run this test case, comment it back again so that your program can reach your subsequent test cases.

Objective 1 for this lab

Your first objective today is to write code in the constructor which ensures that the second class invariant is never violated. Insert your code in the following section of the constructor:
/*
 * Insert class invariant#2 checking code here
 */
You should then write a test case (or more than one test cases) in the main method that checks if the above code works. Your test case should go in the following section of main():
/*
 *Enter test case to check class invariant#2 
 */