Java Reference
In-Depth Information
Because the value of
c
on line 2 can only be
RED
,
GREEN
, or
BLUE
and the
switch
statement
has a
case
for all three of these outcomes, you can assert that line 12 is not reachable. This
example is typical of when to use an assertion. I insist with all certainty that line 12 will not
execute. Notice that if it does, an
AssertionError
is thrown because the
boolean
is
false
.
The only way this assertion would fail is if somehow the enum is modifi ed. Suppose you
are working on a project that uses the
Colors
enum, and during the development phase it is
discovered that yellow needs to be added to the list of colors. The assertion can help uncover
the ripple effect of such a change. Suppose the new version of
Colors
looks like this:
1. public enum Colors {
2. RED, GREEN, BLUE, YELLOW
3. }
See if you can determine the output of the following
main
method added to the
TestColors
class:
public static void main(String [] args) {
Colors c = Colors.YELLOW;
testColor(c);
}
Because
YELLOW
is a new color and not one of the cases, the
default
block executes and
the
assert
fails. (It has to fail because it uses
false
for the
boolean
expression.) Assuming
assertions are enabled, an
AssertionError
is thrown and the following stack trace displays:
Exception in thread “main” java.lang.AssertionError: Invalid color
at TestColors.testColor(TestColors.java:12)
at TestColors.main(TestColors.java:18)
A control fl ow assertion is a common use of
assert
statements. When possible, place an
assert
statement at any location in your code that you assume will not be reached.
Assertions Should Not Alter Outcomes
Because assertions can and probably will be turned off in a production environment, your
assertions should not contain any business logic that affects the outcome of your code.
For example, the following assertion is not a good design because it alters the value of a
variable:
int x = 10;
assert ++x > 10; //Not a good design!
When assertions are turned on,
x
is incremented to
11
, but when assertions are turned
off, the value of
x
is
10
. Therefore, the outcome of the code will be different, and
assert
statements should have no effect on your application if they are turned off, so this is not
a good use of assertions.
Search WWH ::
Custom Search