0

Following this question: Avoiding != null statements I asked one of our senior developers why wouldn't why use assertions. While his answer proved reasonable (we use custom exceptions), he also claimed that assertions are meant to be used while developing and testing, but not in production.

But in Oracle's documentation http://docs.oracle.com/javase/6/docs/technotes/guides/language/assert.html it looks like assertions are meant to be used beyond testing, even more given the possibility of disabling them.

So, is there any better reason or good practice not to use assertions?

Community
  • 1
  • 1
Luis Sep
  • 2,384
  • 5
  • 27
  • 33

1 Answers1

0

Assertions behave differently depending on the language. In C, they are often used incorrectly, and the incorrect usage is so common that many advise that they not be used at all. They should not be used in production (ie, production compiles of C should define NDEBUG for the preprocessor) as they only serve to slow down execution.

The purpose of an assertion is to state a logical necessity, not to check a result. For example it is correct (in C) to write:

f = malloc( s );
if( f == NULL ) {
   ...; exit( 1 );
}
assert( f != NULL );   # This is logically necessary.

But completely wrong to ever write:

f = malloc( x );        # THIS IS AN EXAMPLE OF INCORRECT USAGE
assert( f != NULL );    # DO NOT DO THIS

This is actually useful, since it is perfectly valid to write:

f = xmalloc( x );
assert( f != NULL ); 

Which acts as documentation to the reader that xmalloc is defined in such a way that it will never return a null value.

They are often used at the start of functions:

void f( void *p ) { assert( p != NULL ); ... }

Such usage is not an error check. Rather it serves to indicate that the function f expects that it will never be passed a null pointer. It is documentation to developers that passing a null pointer to f is a programming error. Making it an assertion enables the error to be detected at run time when assertions are enabled.

William Pursell
  • 204,365
  • 48
  • 270
  • 300
  • I guess there are some differences in C and Java when it comes to using assertions. It is also said in that documentation page "Do not use assertions for argument checking in public methods". – Luis Sep Feb 20 '13 at 17:07