Java Reference
In-Depth Information
Using Assertions
Confusion may arise as to when to use assertions in a program. An assertion is implemented in Java by adding a new
class, java.lang.AssertionError , into the existing exception class hierarchy. Sometimes programmers mistake an
assertion as another exception. This may be true when you just look at the class hierarchy and you may say that it is
just another class in the existing exception class hierarchy. However, the similarity between exceptions and assertions
stops right there in the class hierarchy. The main difference lies in the reason behind their usage. An exception is used
to handle a user's error and business rules implementation. If it is possible to recover from exceptional conditions,
you want to recover from them and proceed with the application. An assertion is used to detect programming errors
made by programmers. You do not want to recover from a programming error and proceed with the application.
Assertions are used to verify that what a programmer assumes about his program at a specific point in his code is true.
You should never use an assertion to handle a user's error or to validate data, because assertions are not meant to be
enabled in the production environment.
Assertions should not be used to validate data arguments for public methods. The following snippet of code is
for a credit() method of the BankAccount class, which uses assertion to validate the amount being credited:
// An incorrect implementation
public void credit(double amount) {
assert amount > 0.0 : "Invalid credit amount: " + amount;
// Other code goes here
}
The code for the credit() method depends on enabling an assertion to validate the amount of credit to an
account. Most likely, the assertion will be disabled in the production environment, which will allow a credit of even a
negative number. Such validations for a public method's arguments should be performed using exceptions, as shown:
// A correct implementation
public void credit(double amount) {
if (amount <= 0.0) {
throw new IllegalArgumentException("Invalid credit amount:" + amount);
}
// Other code goes here
}
You can use assertions to validate a method's arguments for a non-public method. A non-public method
cannot be called by clients directly. If a method's parameters for a non-public method are incorrect, it indicates the
programmer's errors and use of assertions is appropriate.
You should not use an assertion that has side effects, such as an assertion that modifies the state of an object.
Consider the following snippet of code in a method assuming that reComputeState() alters the state of the object of
the class:
assert reComputeState();
When this assert statement is executed, it will alter the state of the object. The subsequent interaction with the
object depends on its altered state. If the assertions are disabled, this code will not execute and the object will not
behave properly.
 
Search WWH ::




Custom Search