Java Reference
In-Depth Information
The terms precondition and postcondition refer to particular kinds of
state assertion. A precondition is something that must be true before a
particular chunk of code (usually a method) is executed; a postcondition
must be true after. You can use assert to check pre- and postconditions,
such as:
public boolean remove(Object value) {
assert count >= 0;
if (value == null)
throw new NullPointerException("value");
int orig = count;
boolean foundIt = false;
try {
// remove element from list (if it's there)
return foundIt;
} finally {
assert ((!foundIt && count == orig) ||
count == orig - 1);
}
}
Here the method enforces the precondition that the list size must be
non-negative before the operation, and the postcondition that the list
size should be reduced by one after removal of an element, unless the
element was not in the list.
Note that the check for whether the element to remove is null is not an
assert, but instead throws a NullPointerException . In general you should
expect that users of your class will make mistakes, and so, where pos-
sible, you should always check for them and have defined what happens
for when they make them, such as returning a flag value or throwing an
exception. In effect an assertion is a way of checking that there are no
bugs or unexpected usage in the code, not that the code that calls it is
bug freeso do not use assertions to validate arguments passed to your
non-private methods.
 
Search WWH ::




Custom Search