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:
http://java.sun.com/j2se/1.4/docs/guide/lang/assert.html
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
benefit.
Henri: Java assertions throw AssertionError. JUnit does provide some
basic assertion facilities, but only for test classes.
Cheers,
Paul
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 http://eidola.org http://innig.net
--
To unsubscribe, e-mail: <mailto:commons-dev-unsubscribe@jakarta.apache.org>
For additional commands, e-mail: <mailto:commons-dev-help@jakarta.apache.org>
|