Recipe 1.12 Maintaining Program Correctness with Assertions


You want to leave tests in your code but not have runtime checking overhead until you need it.


Use the JDK 1.4 Assertions mechanism.


JDK 1.4 introduced a new keyword into the language: assert. The assert keyword takes two arguments separated by a colon (by analogy with the conditional operator): an expression that is asserted by the developer to be true, and a message to be included in the exception that is thrown if the expression is false. To provide for backward compatibility with programs that might have used "assert" as an identifier name on prior JDK versions, JDK 1.4 requires a command-line switch (-source 1.4) that must be provided for assert to be recognized as a keyword. Normally, assertions are meant to be left in place (unlike quick and dirty print statements, which are often put in during one test and then removed). To reduce runtime overhead, assertion checking is not enabled by default; it must be enabled explicitly with the -enableassertions (or -ea) command-line flag. Here is a simple demo program that shows the use of the assertion mechanism:

ian:147$  cd testing; ian:148$ cat public class AssertDemo {         public static void main(String[] args) {                 int i = 4;                 if (args.length == 1) {                         i = Integer.parseInt(args[0]);                 }                 assert i > 0 : "i is non-positive";                 System.out.println("Hello after an assertion");         } } ian:149$ javac -source 1.4  # will not compile without 1.4 flag ian:150$ java AssertDemo  -1 Hello after an assertion ian:151$ java -ea  AssertDemo  -1 Exception in thread "main" java.lang.AssertionError: i is non-positive         at AssertDemo.main( ian:152$

Java Cookbook
Java Cookbook, Second Edition
ISBN: 0596007019
EAN: 2147483647
Year: 2003
Pages: 409
Authors: Ian F Darwin

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: