What is a Class Invariant?
A Class Invariant is a property of your data that must be maintained throughout
the lifecycle of your class.
-
Example #1: Shapes cannot have negative sides. They cannot have zero sides either,
so if we were making a Shape class, we need to maintain these properties.
-
Example #2: Rectangles must have four 90 degree corners. This was extra credit last week, remember?.
A Precondition is something that must be true before we call a function. This includes the parameters of the function.
-
In this lab, we will check for Preconditions
Often, we construct preconditions to avoid violating the class invariants.
In the following code for example, the first if statement checks the
Precondition that upholds the Class Invariant (positive sides).
Inside the main method below, a test case is created that violates this precondition (sides is -1).
public Shape(int numSides) {
if(numSides < 1) {
throw new RuntimeException("Number of sides must be positive");
}
...
}
public static void main(String[] args) {
//Test shape
Shape s = new Shape(-1);
}