Java Reference
In-Depth Information
Purpose:
To assert that a condition is fulfilled. If assertion checking is enabled and the
condition is false, an assertion error is thrown.
You can also use the shortcut -ea instead of -enableassertions . You
definitely want to turn assertion checking on during program development and testing.
You don't have to use assertions for checking preconditionsȌthrowing an exception
is another reasonable option. But assertions have one advantage: You can turn them
off after you have tested your program, so that it runs at maximum speed. That way,
you never have to feel bad about putting lots of assertions into your code. You can
also use assertions for checking conditions other than preconditions.
Many beginning programmers think that it isn't Ȓniceȓ to abort the program when a
precondition is violated. Why not simply return to the caller instead?
public void deposit(double amount)
{
if (amount < 0)
return; // Not recommended
balance = balance + amount;
}
That is legalȌafter all, a method can do anything if its preconditions are violated. But
it is not as good as an assertion check. If the program calling the deposit method has a
few bugs that cause it to pass a negative amount as an input value, then the version
that generates an assertion failure will make the bugs very obvious during testingȌit
is hard to ignore when the program aborts. The quiet version, on the other hand, will
not alert you, and you may not notice that it performs some wrong calculations as a
consequence. Think of assertions as the Ȓtough loveȓ approach to precondition
checking.
When a method is called in accordance with its preconditions, then the method
promises to do its job correctly. A different kind of promise that the method makes is
called a postcondition. There are two kinds of postconditions:
1. The return value is computed correctly.
2. The object is in a certain state after the method call is completed.
Search WWH ::




Custom Search