Debugging code is a topic that people do not find particularly interesting, but it is vital to the software development cycle. Detecting bugs early saves money. It is estimated that software bugs missed at requirements definition stage can cost 5 times more to fix during design, 10 times more to fix during coding, 20 times more to fix during unit testing and 200 times more to fix after the software has been delivered. The first defense against bugs are assertions. Assertions contain Boolean statements that confirm the state of the program at a point in the source code. With the release of J2SE 1.4 Assertions were introduced into the Java language. Here is a code example to show assertions in use. The line public class AssertionTest { public static void main(String[] args) { String s; s = new String("Hello World!"); //code here... //e.g. s=null; assert s!=null; //System.out.println(s); //Call something important and pass s } } In this program if Exception in thread "main" java.lang.AssertionError at AssertionTest.main(AssertionTest.java:11) This will only occur if we have 'turned on' assertions in the virtual machine. We can do this by passing the flag In this section of code we can assume that It is worth mentioning that assertions exist in C++ also, but we do it by calling a standard function There are some additional functionality with assertions in Java. For example, we can display a message when an assertion exception occurs. public static void main(String[] args) { ... assert s!=null : "The String S is Null"; ... } which results in the following exception when the assertion evaluates to false (i.e. s is null): Exception in thread "main" java.lang.AssertionError: The String S is Null at AssertionTest.main(AssertionTest.java:11) So, assertions allow for conditional testing of our code, where importantly, we can turn off the checks once we have ensured that the code is working correctly. Assertions can therefore play a valuable role in debugging and designing code, while keeping testing in mind. |