Re: the java assert mechanism: is it useful?
On Aug 4, 4:56 pm, marlow.and...@googlemail.com wrote:
I am familiar with the idea of assertions, from my days with C/C++
(assert.h) and from what Bertrand Meyer says about them in OOSC(II).
And it seems to me that the java assert mechanism is similar. But I
reckon I would never use it for the same reason that I never used the
assert mechanism in C/C++. I preferred to throw an exception that
basically meant a fatal programming error has occurred. It would
always throw if triggered, there was not a mode for production that
made it a no-op. Checking was always on.
The reason I preferred a solution that always checked was because all
too often I come across code that contains assert compiled so that it
is turned off. The code goes wrong but the assertions designed to
detect this never trigger, the program just blows up or otherwise goes
So do people actually find the java assert mechanism useful? I am
relatively new to java and have not seen it used in any projects I
have been on yet. But I do see lots of advice telling newcomers to use
it and how good it is. Does anyone here prefer to always have the
Assertions and exceptions have radically different purposes.
Exceptions are production-time mechanisms to detect anomalous
circumstances, like an interrupted connection or null pointer.
Assertions are a development-time mechanism to ensure algorithmic
Assertions typically are disabled in production. Exceptions must not
be, and indeed cannot be.
Assertions verify that which is under the developer's control, like
the validity of arguments to a private method. Exceptions alert
operations staff to that which is not under the developer's control,
like the validity of arguments to a public method.
Assertions verify that which the programmer thinks that they've
guaranteed. For example,
public final void setFoo( Foo value )
if ( value == null )
final String msg = "null value passed to foo()";
throw new IllegalArgumentException( new
NullPointerException( msg ));
this.foo = value;
assert this.foo != null;
public final Foo getFoo()
assert this.foo != null;
This example is somewhat trivial but illustrates that the assertion
represents the programmer's guarantee that 'getFoo()' cannot return
'null'. It guards against someone down the road commenting out the
'throw', for example, or adding another method that nulls the
attribute. Another use case places an assertion after the call to a
polymorphic method, where the risk is that a subclass might violate a
Invariants are what assertions enforce. Invariants are points in an
algorithm where one can state with certainty ("assert") that a
necessary condition is true.
There's good material on the Sun web site explaining the value of
'assert', and when to use or not use it.