Java Keywords (Part XIX): The assert Keyword

Java keyword list

abstract continue for new switch
assert default goto* package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp volatile
const* float native super while
Keyword marked with an asterisk (*) are keywords that, although valid, are not used by programmers.
The assert keyword enables you to test an assumption about a part of your program. If the assertion is proven to be true, execution of your program will continue. If it's proven to be false, an AssertionError will be thrown. Assertions confirm your assumptions about the behavior of your program, thus increasing confidence that the program is free of errors.

This keyword has been part of the Java language since Java 1.4.2 and yet, very little is known about the correct way to use it. The web is full of misinformation and bad examples on how to correctly use it. With regards to usage, it is meant to be used during development and testing. It is not meant to be used in deployed software. For this reason, the architects of the Java language provided a mechanism to turn assertions on and off. More on this later on.

The simple usage form of the assert keyword is as follows

assert booleanExpression;

Suppose you write a function that produces a String that must be between 8 to 15 characters in length. A valid assertion statement for this requirement will be to check the length of the output of this function:


String result = generateString(...);
int length = result.length();
assert length >= 8 && length <= 15;
// the rest of the code
During development or testing phase, you would want to know that, regardless of input to this function, the output will always comply with this string length requirement. If the requirement is met, the code will continue normal execution. If some input causes the assertion to fail, the developer or tester will notice the error. This will allow debugging of the condition that caused the assertion to fail.

The above scenario is often coded using an if/else flow control structure like the one below:


String result = generateString(...);
int length = result.length();
if (length > 8 || length > 15) {
    throw new Exception("Result string not between 8 and 15 characters in length");
}
// the rest of the code
Logically, this if statement accomplishes the same result: it will throw some exception if the requirement is not met. However, there is a major drawback to this approach. The drawback is that you cannot turn it off for deployed software. So, how developers (usually) turn this check off on production code? One approach I have seen (and one I have to shamefully admit I have done in the past) is to create a boolean flag that is set on some property file.

InputStream input = new FileInputStream("path/to/config.properties");
Properties prop = new Properties();
props.load(input);
boolean isDebug = prop.getProperty("debugFlag");

String result = generateString(...);
int length = result.length();
if (isDebug && (length > 8 || length > 15)) {
    throw new Exception("Result string not between 8 and 15 characters in length");
}
// the rest of the code
Do you see how much boilerplate code is generated to skip this check if in production? Can you see the possibility of this property file value to be accidentally checked in to the code repository? In constrast, the Java Virtual Machine (JVM) disables assertions by default and only turns assertions on if the -enableassertions switch, or its short version -ea, is used to execute the code. If you execute your code inside a development environment (like Eclispe), this switch might be set out of the box in the IDE's VM arguments. So, keep that in mind. The second form of the assert keyword is as follows

assert booleanExpression : expression;

where expression is an expression that has a value. Therefore, you cannot invoke a method that returns void. The purpose of this expression (the value after the colon) is to pass it to the AssertionError constructor in order to provide a more meaningful error message. Using the same example as before:

String result = "Hello";
int length = result.length();
assert length >= 8 && length <= 15 : "string length less than 8 or longer than 15";
// the rest of the code
If executed with assertions enabled, the execution will produce the following assertion error: Exception in thread "main" java.lang.AssertionError: string length less than 8 or longer than 15 You could pass primitive values as well as objects as an expression. For example, you could pass an enum to pass the enum name to the assertion error constructor. The link below shows an example of this.

Required reading

My suggestion is that you go to the Oracle Java website, and read about assertions in Java before you use them.

Comments

Popular posts from this blog

Combining State and Singleton Patterns to Create a State-Machine

Exception Handling: File CRUD Operations Example

The Beauty of the Null Object Pattern