Java Reference
In-Depth Information
Using Assertions
We use assertions for many reasons, including the following:
Internal invariants You assert that a value is within a certain constraint. assert x < 0 is
an example of an internal invariant.
Class invariants You assert the validity of an object's state. Class invariants are typically
private methods within the class that return a boolean . The upcoming Rectangle class
demonstrates a class invariant.
Control flow invariants You assert that a line of code you assume is unreachable is never
reached. The upcoming TestColors class demonstrates a control fl ow invariant.
Preconditions You assert that certain conditions are met before a method is invoked.
Post conditions You assert that certain conditions are met after a method executes
successfully.
The following example demonstrates a control fl ow invariant. Suppose we have the
following enum declaration:
1. public enum Colors {
2. RED, GREEN, BLUE
3. }
The following TestColors class contains a switch statement that switches on a Colors
object. Because there are only three possible outcomes, the default statement on line 11
should never execute:
1. public class TestColors {
2. public static void testColor(Colors c) {
3. switch(c) {
4. case RED :
5. case GREEN :
6. System.out.println(“Red or green”);
7. break;
8. case BLUE :
9. System.out.println(“Blue”);
10. break;
11. default :
12. assert false : “Invalid color”;
13. }
14. }
15.}
Search WWH ::




Custom Search