Testing Pre- and Post-Conditions
In many cases, your methods will not work with certain inputs. The primary example is how will your method behave if it is passed a null pointer? Throwing a null pointer exception is fine, but sometimes you can get other unexpected behavior. There are many more elegant ways to handle the passing of a null pointer, so always check to make sure your preconditions are met.
public static void main(String[] args) {
//Test open cash
openCashRegister(null);
}
public static void openCashRegister(CashRegister cash) {
if(cash == null) {
return;
}
...
}
Think about your Fraction class and the equals() method. How does it handle 2/3 == 4/6? How could you fix this? Is there a way to handle this issue through the class invariant? What happens when the multiply() method is passed a null reference?Think about your
Point class. What happens when the distance() method is passed a null reference?Think about your
Rectangle class. What happens when the toString() method of the Point class is modified?- Modify your code to handle the pre- and post- conditions for all of these methods.