Java Reference
In-Depth Information
You can use assertions to implement class invariants. Class invariants are conditions that always hold true about
the values that determine the state of an object of a class. Class invariants may not be true for brief moments when an
object is transitioning from one state to another. Suppose you have a BankAccount class with four instance variables:
name , dob , startDate , and balance . The following class invariants must be true for a BankAccount object:
The
name on the account must not be null .
The
dob on the account must not be null and must not be a date in future.
The
startDate on the account must not be null .
The
startDate on the account must not be before dob .
balance on the account must be greater than zero.
You can pack all these conditions checks in one method, say validAccount() method.
The
private boolean validAccount() {
boolean valid = false;
// Check for class invariants here. Return true if it is true. Otherwise, return false.
return valid;
}
You can use the following assertion in methods and constructors to make sure that the class invariants are
enforced. You assume that the toString() method of the BankAccount class returns enough pieces of information to
help programmers debug the error.
assert validAccount(); this.tostring();
You can use the above assert statement in the beginning of every method and before you return from the
method. You do not need to check for class invariants inside a method if it does not modify the object's state. You
should use it only at the end in a constructor because class invariants will not hold when the constructor starts
executing.
Checking for Assertion Status
How do you know in your program if assertions are enabled? It is easy to check for the assertion status using an
assert statement. Consider the following snippet of code:
boolean enabled = false;
assert enabled = true;
/* Check the value of enabled here */
This code uses the first form of the assert statement. Note that it uses the assignment operator (=), not the
equality comparison operator ( == ) in the expression enabled = true . The expression will assign true to the enabled
variable and it will evaluate to true . Note that the enabled variable has been initialized to false . If assertion is
enabled, the enabled variable will have a value of true after the assert statement is executed. If assertion is disabled,
the variable enabled will have a value of false . Therefore, checking for the value of the enabled variable after the
assert statement will give you a clue whether assertions are enabled for your class. Listing 10-2 shows the complete
code for checking if assertions are enabled for the AssertionStatusTest class. Note that assertion can be enabled or
disabled on a class basis, too. If assertions are enabled for a specific class, it does not guarantee that it is also enabled
for all other classes.
 
Search WWH ::




Custom Search