commons-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Paul `Order in Chaos` Cantrell <>
Subject Re: [Lang] Assertions?
Date Mon, 21 Oct 2002 14:37:15 GMT
Here's a page explaining 1.4's assertions.  I highly recommend reading 
it -- it will short-circuit a lot of the discussion that Ola's question 
is bound to generate:

JDK 1.4's assertion facilities make most of Ola's examples too trivial 
to warrant helper methods, IMO -- the following all seem quite clear 
and concise :

     assert object != null;
     assert array.length != 0;
     assert !coll.isEmpty();
     assert str.size() != 0;

Note that one can also do this:

     assert (result != null) : "foo() result is null; expected bar 
element in" + elements;

An assertion utility could, of course, take the string argument:

     Assert.notNull(result, "foo() result is null; expected bar element 
in " + elements);

However, the Java version has a big advantage: In the latter example, 
the code will *always* call elements.toString() -- even if the 
assertion succeeds, and even if assertions are turned off!  The Java 
native version doesn't evalutate the condition unless assertions are 
enabled, and doesn't evaluate the message unless the assertion fails.

The only one of the examples in Ola's message that isn't trivial with 
1.4's assert is "noNullElements".  If there is actually a need for 
assert utilities, it's for deeper structural checks like that.

What does seem much more generally useful is a hasNullElements() 
method, which would make the assertion easy to write as a nice side 

Henri: Java assertions throw AssertionError.  JUnit does provide some 
basic assertion facilities, but only for test classes.



On Monday, October 21, 2002, at 09:12  AM, Henri Yandell wrote:

> First thoughts on assertion code:
> Does JUnit already have this? What do we feel about JUnits version if 
> it
> does? Does JDK 1.4 contain much more than the 'assert' keyword?
> What does 1.4 throw when an assertion fails?
> Hen
> On Mon, 21 Oct 2002, Ola Berg wrote:
>> How about utilities for assertions?
>> I can imagine:
>> class Assert
>>     notNull( Object)
>>     noNullElements( Object[])
>>     notEmpty( Object[]) //works for collections too
>> plus either adding methods for common object types:
>>     notEmpty( String)
>> or adding assert* methods to the lang *Utils:
>>     assertNotEmpty( String)
>> When an assertion fails, the methods will throw 
>> IllegalArgumentException
>> Good or bad? I can do the coding, if people like it.
>> /O
   Paul Cantrell

To unsubscribe, e-mail:   <>
For additional commands, e-mail: <>

View raw message