Java Reference
In-Depth Information
Good Programming Practice 11.3
By convention, all exception-class names should end with the word
Exception
.
Programmers spend significant amounts of time maintaining and debugging code. To fa-
cilitate these tasks and to improve the overall design, you can specify the expected states
before and after a method's execution. These states are called preconditions and postcon-
ditions, respectively.
Preconditions
A
precondition
must be true when a method is
invoked
. Preconditions describe constraints
on method parameters and any other expectations the method has about the current state
of a program
just before it begins executing
. If the preconditions are
not
met, then the meth-
od's behavior is
undefined
—it may
throw an exception
,
proceed with an
illegal value
or
at-
tempt to recover
from the error. You should not expect consistent behavior if the
preconditions are not satisfied.
Postconditions
A
postcondition
is true
after the method successfully returns
. Postconditions describe
con-
straints on the return value
and any other
side effects
the method may have. When defining
a method, you should document all postconditions so that others know what to expect
when they call your method, and you should make certain that your method honors all its
postconditions if its preconditions are indeed met.
Throwing Exceptions When Preconditions or Postconditions Are Not Met
When their preconditions or postconditions are not met, methods typically throw excep-
tions. As an example, examine
String
method
charAt
, which has one
int
parameter—an
index in the
String
. For a precondition, method
charAt
assumes that
index
is greater
than or equal to zero and less than the length of the
String
. If the precondition is met, the
postcondition states that the method will return the character at the position in the
String
specified by the parameter
index
. Otherwise, the method throws an
IndexOutOfBounds-
Exception
. We trust that method
charAt
satisfies its postcondition, provided that we
meet the precondition. We need not be concerned with the details of how the method ac-
tually retrieves the character at the index.
Typically, a method's preconditions and postconditions are described as part of its
specification. When designing your own methods, you should state the preconditions and
postconditions in a comment before the method declaration.
When implementing and debugging a class, it's sometimes useful to state conditions that
should be true at a particular point in a method. These conditions, called
assertions
, help
ensure a program's validity by catching potential bugs and identifying possible logic errors
during development. Preconditions and postconditions are two types of assertions. Pre-
conditions are assertions about a program's state when a method is invoked, and postcon-
ditions are assertions about its state after a method finishes.