Java Reference
In-Depth Information
might have to run this application a few times to see the assertion error, but first you
need to learn how to enable assertions, which I discuss later in this chapter.)
Caution Be careful when using an assertion statement to detect code that should
ever be executed. If the assertion statement cannot be reached according to the rules
set forth in The Java Language Specification, Third Edition, by James Gosling, Bill
Joy,GuySteele,andGiladBracha(Addison-Wesley,2005;ISBN:0321246780)(also
available at ( http://java.sun.com/docs/books/jls/third_edition/
html/j3TOC.html ) , the compiler will report an error. For example, for(;;);
assert false; causesthecompilertoreportanerrorbecausetheinfiniteforloop
prevents the assertion statement from executing.
Design-by-Contract
Design-by-Contract (see http://en.wikipedia.org/wiki/
Design_by_contract ) is a way to design software based on preconditions, post-
conditions,andinvariants(internal,control-flow,andclass).Assertionstatements sup-
port an informal design-by-contract style of development.
Preconditions
A precondition issomethingthatmustbetruewhenamethodiscalled.Assertionstate-
mentsareoftenusedtosatisfyahelpermethod'spreconditionsbycheckingthatitsar-
guments are legal. Listing 3-36 provides an example.
Listing 3-36. Verifying a precondition
class Lotto649
{
public static void main(String[] args)
{
// Lotto 649 requires that six unique umbers be
chosen.
int[] selectedNumbers = new int[6];
// Assign a unique random umber from 1 to 49 (inclus-
ive) to each slot
// in the selectedNumbers array.
for (int slot = 0; slot < selectedNumbers.length;
slot++)
{
 
Search WWH ::




Custom Search