dcsimg

Assert Yourself

Because Linux is now one of the primary platforms for Java development, developers have good reason to take advantage of each new Java release as soon as it's available. Java 2 Standard Edition version 1.4 (J2SE 1.4), the fifth major release of Java, was released back in March and is packed full of valuable new features. According to "Java in a Nutshell" author David Flanagan, there are 62 percent more classes and interfaces in J2SE 1.4 than its predecessor, Java 1.3.

Because Linux is now one of the primary platforms for Java development, developers have good reason to take advantage of each new Java release as soon as it’s available. Java 2 Standard Edition version 1.4 (J2SE 1.4), the fifth major release of Java, was released back in March and is packed full of valuable new features. According to “Java in a Nutshell” author David Flanagan, there are 62 percent more classes and interfaces in J2SE 1.4 than its predecessor, Java 1.3.

If you haven’t upgraded or tried J2SE 1.4 yet, you can download it from Sun’s Web site at http://java.sun.com/j2se/1.4/download.html. Linux users can install it in two forms: a Red Hat RPM shell script and a GNUZIP tar shell script. J2SE 1.4 includes the Java Runtime Environment, an interpreter for users running Java programs, and the Java 2 Software Development Kit, a set of packages and command-line tools that can be used to write, compile, run, and debug Java programs.

This month’s column continues our look at J2SE 1.4. The J2SE 1.4 chained exception feature was covered in June (available online at http://www.linux-mag.com/2002-06/java_01.html), and the new Java regular expression classes were covered in July (also available online at http://www.linuxmagazine/2002-07/java_01.html). This month we introduce the new assert feature.

A Shiny New Keyword

Of all the new offerings in J2SE 1.4, the one getting the most attention is Sun’s addition of a new keyword, assert. Keywords don’t get added often to the language, but this one is part of the introduction of assertions, a design technique for improving the reliability of code.

(Assertions almost made it into the first release of Java. Language creator James Gosling included the feature in the early 1990s when Java was known as “Oak” and was being developed for a consumer electronics project at Sun. Assertions were reportedly removed to help Java meet a deadline.)

An assertion is a boolean expression that represents something a programmer believes to be true at the point of the assertion. Assertions are a way to provide some assurance to yourself that your program is running as expected. Assertions are expressed with the brand-new assert keyword like this:


assert (position < 0);

This statement asserts that a variable named position has a value less than 0. If position equals 0 or more at this spot in the program, it’s a sign that things are completely fubar (in other words, very broken).

The assert keyword must be followed by a boolean expression, a boolean variable, or a method that returns a boolean value. If the boolean result is not true, an AssertionError exception will be thrown. You can make an assertion more meaningful by specifying an error message in an assert statement, which will be used if an exception is thrown:


assert (position < 0) :
“Submarine above sea level!”;

The previous line says, “If the position of the submarine is not less than zero, then throw an exception with the message ‘Submarine above sea level!’”

Here’s an example of how the SDK’s interpreter responds when an uncaught AssertionError is thrown.


Exception in thread “main”
java.lang.AssertionError: Submarine above sea
level! at Submarine.move(Submarine.java:1814)

Although assertions are a standard part of J2SE 1.4, they are turned off by default in the tools included with the J2SE 1.4 SDK. (The same is likely to be true in other Java development tools.) You must use explicit command-line arguments to enable assertion support in the SDK compiler and interpreter.

Switch On

To compile a class that contains assert statements, use the -source 1.4 option, like so:


javac -source 1.4 Submarine.java

The -source 1.4 option causes the compiler to produce bytecode that supports assertions in the resulting class file (or files). If you have assert statements in the file, but do not use this option, the class will not compile.

In the SDK’s Java interpreter, you can turn on assertions for all of your classes, a specific class, or a specific package.

To enable assertions in all of your classes run by the interpreter, use the -ea argument:


java -ea Submarine

To enable assertions only in one class, follow -ea with a colon (“:”) and the name of the class:


java -ea:Submarine Submarine

To enable assertions only in one package, follow -ea with a colon (“:“) and the name of the package:


java -ea:com.prefect.marine Submarine




Listing One: assert protects against bad arguments


public class Sabermetrician {
public static float getERA(float earnedRuns, float inningsPitched) {
assert earnedRuns > = 0.0;
assert inningsPitched > = 0.0;
float inningERA = earnedRuns / inningsPitched;
return inningERA * 9F;
}

public static void main(String[] arguments) {
if (arguments.length > 1) {
try {
float er = Float.parseFloat(arguments[0]);
float ip = Float.parseFloat(arguments[1]);
System.out.println(“Earned Runs: ” + er);
System.out.println(“Innings Pitched: ” + ip);
System.out.println(“Earned Run Average: ” +
Sabermetrician.getERA(er, ip));
} catch (NumberFormatException nfe) {
System.out.println(nfe.getMessage());
}
}
}
}

The code in Listing One contains Sabermetrician, a Java class with a class method, getERA(), that calculates a baseball pitcher’s earned-run average, one of several thousand statistics that have meaning to a sabermetrician — a hardcore math-loving baseball fan who swap statistics with members of his (or her) own kind.

The getERA() method takes two floating-point arguments: earned runs and innings pitched. The class assumes that both of these arguments will always have a value of 0 or higher. To test and enforce those assumptions, the class uses assert statements.

Save the code into Sabermetrician.java, compile the class with assertion support enabled, and run it with two command-line arguments: the number of earned runs and innings pitched. Try it in several ways: use positive numbers, negative numbers, assertions enabled, and assertions disabled. Here is a sample of building and running the class.


% javac Sabermetrician.java
Sabermetrician.java:3: warning: as of
release 1.4, assert is a keyword,
and may not be used as an identifier
assert earnedRuns >= 0.0;

% javac -source 1.4 Sabermetrician.java
% java -classpath . -ea Sabermetrician 1 5
Earned Runs: 1.0
Innings Pitched: 5.0
Earned Run Average: 1.8000001
% java -classpath . -ea Sabermetrician -1 5
Earned Runs: -1.0
Innings Pitched: 5.0
Exception in thread “main” java.lang.AssertionError at
Sabermetrician.getERA(Sabermetrician.java:3) at
Sabermetrician.main(Sabermetrician.java:16)
% java -classpath . Sabermetrician -1 5
Earned Runs: -1.0
Innings Pitched: 5.0
Earned Run Average: -1.8000001

As you can see, when assertions are enabled, any negative number used as an argument causes an AssertionError exception to be thrown.

Assertions, chained exceptions, and regular expressions are only a sampling of the significant changes in J2SE 1.4 (many Java programmers who wandered over from Perl are geeked about the first-time support for regular expressions in the javax.util.regex package). There’s also a new logging package (not to be confused with Apache Log4j, which was covered last month in this column), a preferences package for system-wide application configuration, and a great feature for server programmers: enhanced networking that supports buffers, secure sockets, non-blocking input and output, buffers, and secure sockets.

Enhanced networking will be the subject of next month’s column. We’ll use the new java.nio package to create a Finger server in Java.



Rogers Cadenhead is a Web application developer and the coauthor of Teach Yourself Java 2 in 21 Days, Third Edition from Sams Publishing. To contact Rogers, visit his weblog at http://workbench.cadenhead.info.

Comments are closed.