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 |
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
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
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
-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 followsassert 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
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.
Next up, Part XX: The strictfp
Keyword
Comments
Post a Comment