Preconditions
Precondition: Requirement that the caller of a method must meet
Publish preconditions so the caller won't call methods with bad parameters
/**
Deposits money into this account.
@param amount the amount of money to deposit
(Precondition: amount >= 0)
*/
Typical use:
To restrict the parameters of a method
To require that a method is only called when the object is in an appropriate state
If precondition is violated, method is not responsible for computing the correct result. It is free to do anything
Method may throw exception if precondition violated – more in Chapter 11
if
(amount < 0) throw new IllegalArgumentException();
balance = balance + amount;
Method doesn't have to test for precondition. (Test may be costly)
// if
this makes the balance negative, it's the caller's fault
balance = balance + amount;
Method can do
an assertion check (click
here for example)
assert amount >= 0;
balance = balance + amount;
To enable
assertion checking:
java
-enableassertions
MyProg
You can turn assertions off after you have tested your program, so that it runs at maximum speed
Many beginning
programmers silently return to the caller
if (amount < 0)
return;
// Not recommended; hard to debug
balance = balance + amount;