commons-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Paul Cantrell <cantr...@pobox.com>
Subject Re: [Lang] Assertions?
Date Mon, 21 Oct 2002 15:47:16 GMT
I think the point they're making here (IIRC, this is Josh Bloch 
writing) is that assertions are for runtime integrity checks that 
should theoretically *never* fail, ever -- things where removing the 
check shouldn't change the behavior of the code.

Assertions are essentially runtime unit testing.

The point is that invariants and postconditions are assertions in this 
model, but _preconditions_ are not if they depend on values supplied by 
the client.  The reasons they give are quite reasonable: (1) a module 
should do defensive checks whether or not assertions are enabled, and 
(2) when a violation of a precondition signals a client programming 
error, the exception should be descriptive.

Argument (2) still seems to rule out generic assertion facilities, 
since what you really want for preconditions are things like this:

     if(hasNullElement(listArg))
         throw new IllegalArgumentException("listArg == null");
     if(destination == null)
         throw new IllegalStateException("provide a destination first");

Again, it doesn't seem like generic assertion utilities have much to 
offer here.  Generic deep structural check utilities seem more useful, 
as in the first example above.

Cheers,

Paul

> Here's what the refered document 
> (http://java.sun.com/j2se/1.4/docs/guide/lang/assert.html) says:
>
> --->8---
> * Do not use assertions for argument checking in public methods.
>
> Argument checking is typically part of the published specifications 
> (or contract) of a method, and these specifications must be obeyed 
> whether assertions are enabled or disabled. Another problem with using 
> assertions for argument checking is that erroneous arguments should 
> result in an appropriate runtime exception (such as 
> IllegalArgumentException, IndexOutOfBoundsException, or 
> NullPointerException). An assertion failure will not throw an 
> appropriate exception.
>
> * Do not use assertions to do any work that your application requires 
> for correct operation.
>
> Because assertions may be disabled, programs must not assume that the 
> boolean expression contained in an assertion will be evaluated.
> ---8<---
>
> The use of Assert (or whatever) I thought of would be precisely that 
> illegal use: to faciliate argument checking in public methods (and 
> throw IAE), in order to enforce object contracts.


--
To unsubscribe, e-mail:   <mailto:commons-dev-unsubscribe@jakarta.apache.org>
For additional commands, e-mail: <mailto:commons-dev-help@jakarta.apache.org>


Mime
View raw message