Java Reference
In-Depth Information
Using Assertions
There are many situations where assertions should be used. These situations organize
intointernalinvariant,control-flowinvariant,anddesign-by-contractcategories.An in-
variant is something that does not change.
Internal Invariants
An internal invariant isexpression-orientedbehaviorthatisnotexpectedtochange.For
example, Listing 3-33 introduces an internal invariant by way of chained if-else state-
ments that output the state of water based on its temperature.
Listing 3-33. Discovering that an internal invariant can vary
class IIDemo
public static void main(String[] args)
double temperature = 50.0; // Celsius
if (temperature < 0.0 )
System.out.println("water has solidified");
if (temperature >= 100.0)
System.out.println("water is boiling into a gas");
// temperature > 0.0 and temperature < 100.0
assert(temperature > 0.0 && temperature < 100.0):
System.out.println("water is remaining in its li-
quid state");
sioncausesthefinal else tobereached.Becausethecommentmightnotbeenoughto
detect the lurking < 0.0 expression bug, an assertion statement is necessary.
Search WWH ::

Custom Search