Java Assertions

Overview

Java assertions are wonderful things which help define the desired behaviour of an application. For example the following assertion states that the variable number should be non-negative:

 assert ( number >= 0) 

Unlike exceptions, which can be caught and handled gracefully, an assertion failure indicates that something has gone terribly wrong within the application and causes it to exit. Thus, in the above example, if assertions are switched on and number is equal to -5 the application will crash.

The Dilemma

There is a question about whether assertions should be switched on in production code.

The argument for switching them off follows the lines of:

Production applications should not suddenly and unexpectedly crash.  Assertions should be left on during testing and switched off during production code.  Adequate logging should be used to ensure any anomalous application states are identified.

The argument for switching them on follows the lines of:

Assertions specify conditions which should never occur. Leaving assertions off in production code may allow the application to run in an unstable state. Failing early allows the problem to be identified and corrected sooner.

The Answer…well sort of

Like all things, the answer will depend on your domain and your needs. Early failure is definitely the way to go however, you may, for some spectacular reason, be in a situation where running an unstable application is preferable to a non-running application.

The biggest problem with assertions however, is not that they cause applications to crash, but that they can slow an application down. Consider an optimised sort method which gets called with a large data set – a few additional expensive assert evaluations could jeopardise the efficiency of the base code.  For this reason, Oracle switches assertions off by default.

The answer then seems to be to have assertions switched on during testing and switched off in production for optimisation reasons. Oh yeah and one other thing, your tests should be really good.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s