Assertions in Java

Sometimes in programming, there are some assumptions that must be true; for example, if you are going to calculate the square root of a number, the number must be positive. To facilitate the test of such assumptions, Java offers the assertion facility, which refers to the verification of a condition that is expected to be true during the execution of a program. It is implemented using the keyword assert, introduced to the Java language in Java 2, version 1.4. The assertion facility can be enabled or disabled during compilation and runtime. This feature is mostly used during development for testing and debugging, and is disabled before the product distribution.

The syntax for using assertions follows:

   assert <condition>;
  or
  assert <condition>:<expression>;

The <condition> must evaluate to a boolean. The <expression> is used to send the error message. If assertions are enabled during compilation and runtime, the condition is evaluated. If the condition is true, no further action is taken; if the condition is false, an AssertionError is thrown. If <expression> is specified, it is passed into the constructor of the AssertionError, where it is used as an error message.

As a demonstration of the assertion facility, consider code listing below:

1. public class AssertionExample{
2.     public static void main(String[] args) {
3.        int x = 15;
4.        DataAccess da = new DataAccess();
5.        assert da.dataIsAccesible():"Data is not acceptable";
6.       System.out.println("Value of x: " + x);
7.     }
8. }

9. class DataAccess {
10.    public boolean dataIsAccesible(){
11.         return false;
12.    }
13. } 

Assertions are disabled by default. To enable assertions, compile and execute above listing with the following commands:

   javac -source 1.4 AssertionExample.java
   java -ea AssertionExample

If you compile and execute the code with these options, the output will be AssertionError with the following message:
 

   Data is not acceptable 

Line 6 will not be executed. If you run the program with the command java AssertionExample the assertion code would be ignored, and the output would be:

  Value of x: 15 

The support for assertions is enabled by default when compiling code in J2SE 5.0. However, assertions are turned off by default during execution of the program. If you want to turn them on, you need to use the –ea (enableassertions) flag. You can also use this flag to turn assertions on only
for specific classes in your application, as shown here:

java –ea:<myClass1> -ea:<myClass2> <myApp>

Similarly, you can turn assertions off in specified classes and packages by using the flag –da, or disableassertions as in the command line here:

   java -disableassertions <myApp>

Note that you do not need to recompile your program to turn the assertions on or off during the execution. This is a function of the class loader. Also note that when the assertions are disabled during execution for a class, the class loader strips off the assertion code, and it does speed up the execution. In other words, by enabling assertions, you do pay the performance price.

Remember that assertion failures are unrecoverable errors, and you only use the assertion mechanism to uncover programming errors during testing of the applications. So, do not handle the assertion errors in the program; you detect them and fix them in the code.

There are certain situations in which you should not use assertions. Following are some examples:
 

• Do not use assertions to check the arguments passed to a public method. There are two reasons for not doing that:
  • If argument checking is needed, it must be part of the method specifications and must become part of the permanent method behavior. Remember that assertions are not always enabled during execution.
  • Erroneous argument passing should result in a more specific and appropriate runtime exception such as IllegalArgumentException, IndexOutOfBoundsException, or NullPointerException.
   This also implies that you should not use assertions to check the command-line arguments.

• Do not use assertions to enforce the correct operation required by your application because, again, assertions may not be enabled during the application execution. You do not want to count on assertions to check the correct behavior of your running application. For example, you want to make sure that a list myList does not have any null elements in it. Doing the following
is an inappropriate use of assertions: 

   assert myList.remove(null);

    This removal will not happen if the assertion is not enabled.

• The expression in an assert statement must not produce any side effects such as modifying the variable values. 

The key factor to remember for the appropriate use of assertions is that assertions are typically used to test and debug an application before its deployment and are not guaranteed to be enabled when the application is running. 

Reference(s): SCJP Exam for J2SE 5  

Newer Post Older Post

Leave a Reply

naeemgik. Powered by Blogger.