Java Reference
In-Depth Information
for (int i = 0; i < b.length; i++)
if (!contains(result, b[i]))
return false;
return true;
}
static boolean contains(int[] a, int val)
{
for (int i = 0; i < a.length; i++)
if (a[i] == val)
return true;
return false;
}
}
Listing3-37 usesanassertionstatementtoverifythepostconditionthatallthevalues
inthetwoarraysbeingmergedarepresentinthemergedarray.Thepostconditionisnot
satisfied, however, because this listing contains a bug.
Listing 3-37 also shows preconditions and postconditions being used together. The
solitary precondition verifies thatthemergedarraylengthequalsthelengthsofthear-
rays being merged prior to the merge logic.
Class Invariants
A class invariant isakindofinternalinvariantthatappliestoeveryinstanceofaclassat
all times, except when an instance is transitioning from one consistent state to another.
For example, suppose instances of a class contain arrays whose values are sorted in
ascendingorder.Youmightwanttoincludean isSorted() methodintheclassthat
returnstrueifthearrayisstillsorted,andverifythateachconstructorandmethodthat
modifies the array specifies assert isSorted(); prior to exit, to satisfy the as-
sumption that the array is still sorted when the constructor/method exists.
Avoiding Assertions
Althoughtherearemanysituationswhereassertionsshouldbeused,therealsoaresitu-
ations where they should be avoided. For example, you should not use assertions to
check the arguments that are passed to public methods, for the following reasons:
• Checkingapublicmethod'sargumentsispartofthecontractthatexistsbetween
themethodanditscaller.Ifyouuseassertionstocheckthesearguments,andif
Search WWH ::




Custom Search