Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / August 2007

Tip: Looking for answers? Try searching our database.

Assertions vs Exceptions ...

Thread view: 
Giovanni Azua - 08 Aug 2007 20:36 GMT
Hi all,

I am developing a framework in Java and facing the question of whether:

- Provide a defensive layer around my framework as part of the API public
contract e.g. throws IllegalArgumentException on invalid input or
"precondition violations".

  Pros)
           > Clear client-provider contract.
           > Allows possible recovery in production mode.

  Cons)
           > Performance

- Do not provide any defensive layers but instead use assertions, so users
of  my framework have the following options:

       a) enable assertions during testing and debugging.
       b) disable assertions once in production mode at the cost of
           possible production faults because of unrecoverable
           "precondition violations" that could lead to infite recursions
           or the like.

  Pros)
           > Performance.

  Cons)
           > Preconditions are not part of the public interface contract.
           > No chance to recover from precondition violations in
production mode.

I posted a thread "Modular Protection vs Assertions" in the following
newsgroup where I include different views on the subject from either Sun
guideliness on assert usage vs guideliness proposed by top figure in OO
Prof. Dr. Bertrand Meyer see:

http://groups.google.com/group/comp.lang.eiffel/browse_thread/thread/a81b46fbf9c
d89c5/273571d8d33088a1#273571d8d33088a1


Any insights?

Which solution would YOU prefer if you were to be the user of a framework?

Best regards,
Giovanni
Stefan Ram - 08 Aug 2007 20:45 GMT
>Cons Preconditions are not part of the public interface contract.

 Why can't they be listed in the public interface
 contract in this case?

>No chance to recover from precondition violations in
>production mode.

 That's allright, you can't recover from everything.

 Every device has its preconditions beyond which it
 will break.
Giovanni Azua - 08 Aug 2007 20:58 GMT
Hi Stefan,

"Stefan Ram" <ram@zedat.fu-berlin.de> wrote in message:
>>Cons Preconditions are not part of the public interface contract.
>
>  Why can't they be listed in the public interface
>  contract in this case?

Well, if you mean you can document assertions in Javadoc, in the Javadocs
you may write whatever you want but Javadocs and the (sad) reality may be
different or become obsolete anytime. Conversely the throws clause e.g.
throwing checked exceptions is part of the method signature and "public
contract".

Regards,
Giovanni

PS: anyway which solution would you prefer? :)
Stefan Ram - 08 Aug 2007 21:25 GMT
>>>Cons Preconditions are not part of the public interface contract.
>>Why can't they be listed in the public interface
>>contract in this case?
>you may write whatever you want but Javadocs and the (sad)
>reality may be different or become obsolete anytime.

 I see. You do not refer to JavaDoc, but Java proper.

 A method »log«, requiring x > 0, could be written as:

double log( final Positive x ){ ... }

 »Positive« would be a class representing positive
 values only.

 This shifts the problem to how to treat:

new Positive( -2.0 )

 But by this shift there might be fewer places in the
 source code where to check, when »Positive« is used often.

 You might want a static (i.e., compile-time) check of the
 contract. But since values can be calculated from run-time
 data, they can not all be checked at compile-time. Moreover,
 such a check might be equivalent to the halting problem.

 A function might be called with an argument for which
 it has unspecified behavior in the following cases:

   - The programmer wants unspecified behavior:
     This is usually is not the case.

   - The programmer made an error:
     This should have been avoided by quality control
     before the production version is being released.

   - External input data are unexpected:
     The program should check external input data.
     The behavior of the program in this case ultimately
     needs to be specified by the customer who orderer
     the program.
Ben Phillips - 09 Aug 2007 02:59 GMT
>>>>Cons Preconditions are not part of the public interface contract.
>>>
[quoted text clipped - 9 lines]
>
> double log( final Positive x ){ ... }

Bleeaaccchhhkk!

A whole new class just for this?

What we really need is for Java 7 to add eiffel-style invariants and
suchlike. Preconditions are specified with a string literal optional and
throw IllegalArgumentException, or maybe NullPointerException for "!=
null" ones. The others throw Error, because they surely indicate a bug
in the called code rather than in the calling code. Postconditions don't
trip if the code explicitly throws, of course, rather than trying to
return normally while violating a postcondition. Class invariants that
go or get left out of whack throw always -- either the class is not
exception safe or it's not thread-safe and got corrupted by a race
condition.

All of them produce javadoc entries.

I think this could be managed without new keywords, by adding a new
usage of "assert", with the risk of confusion (which asserts remain in
effect in production code?) -- the new syntax could be say

assert = precondition (foo >= 0.0 && foo <= 100.0 && foo == foo) "foo is
not a valid percentage"

assert = postcondition and assert = invariant likewise. The latter in a
class body but not a method body being a class invariant; in a loop body
a loop invariant (doesn't throw if the loop exits abnormally via break,
return, or throw).

In this case precondition, postcondition, and invariant are not
keywords; they are recognized specially after the "assert =" token pair
(currently not well-formed Java) and can be used normally as identifiers
without the usages clashing.
Twisted - 09 Aug 2007 03:07 GMT
> >>>>Cons Preconditions are not part of the public interface contract.
>
[quoted text clipped - 33 lines]
> assert = precondition (foo >= 0.0 && foo <= 100.0 && foo == foo) "foo is
> not a valid percentage"

Yuck. This WILL cause confusion as to which asserts are asserts and
which are in-production-code guards, regardless. Why now a new syntax
for "throw" instead? E.g.

throw = precondition (...) "..."
Ben Phillips - 09 Aug 2007 03:14 GMT
Yeesh, that was quick to get sorta shot down. But I think you object
only in some details, not to the main idea...

>>assert = precondition (foo >= 0.0 && foo <= 100.0 && foo == foo) "foo is
>>not a valid percentage"
>
> Yuck. This WILL cause confusion as to which asserts are asserts and
> which are in-production-code guards, regardless.

Yeah, you're probably right.

> Why now a new syntax for "throw" instead? E.g.
>
> throw = precondition (...) "..."

Excellent idea. Actually, why not "throw" for precondition (throws
IllegalArgumentException and remains in production code when asserts are
disabled) and "assert" for the others, and the latter behave as special
forms of regular asserts? (i.e. throw Errors, are disabled in production
code when asserts are disabled, etc.)
Thomas Hawtin - 08 Aug 2007 20:59 GMT
> - Provide a defensive layer around my framework as part of the API public
> contract e.g. throws IllegalArgumentException on invalid input or
> "precondition violations".

>    Cons)
>             > Performance
>
> - Do not provide any defensive layers but instead use assertions, so users
> of  my framework have the following options:

In practice argument checking does is very rarely a performance issue.
It's used in low-level APIs and even arrays. High-level checks should
usually be much less frequent than these.

OTOH, the improvements in programmer productivity and being able to
detect errors in live systems is very important. It's a pity more isn't
done be static analysis.

Tom Hawtin
Lew - 08 Aug 2007 23:01 GMT
>> - Provide a defensive layer around my framework as part of the API
>> public contract e.g. throws IllegalArgumentException on invalid input
[quoted text clipped - 13 lines]
> detect errors in live systems is very important. It's a pity more isn't
> done be static analysis.

The conventional wisdom is that assertions are to enforce invariants, and
these are under API developer control.  Sun and others explicitly advise
against using assertions for data validation.  Heed this advice.

Exceptions, particularly checked exceptions and not runtime ones as you
illustrate, exist for the purpose you describe.

Signature

Lew

Mark Rafn - 09 Aug 2007 01:07 GMT
>I am developing a framework in Java and facing the question of whether:
>
>- Provide a defensive layer around my framework as part of the API public
>contract e.g. throws IllegalArgumentException on invalid input or
>"precondition violations".

Do that.  Be very clear in documentation what you expect of your callers, and
check your state and parameters in ways that are clear to callers.

>   Pros)
>            > Clear client-provider contract.
>            > Allows possible recovery in production mode.
>
>   Cons)
>            > Performance

Generally, not much of a con.  Where something is so tight that you really
can't afford parameter validation, you should usually go with a pattern where
there's a call that does a lot of validation which returns a pre-validated
object that can rapidly be reused many times.  But generally, just program
defensively at interface boundaries.

>- Do not provide any defensive layers but instead use assertions, so users
>of  my framework have the following options:

Yick.  Asserts are for turning a hidden bug into an explicit one, and work
best for the person controlling the code.  Don't base your API behavior on
assertion status of your classloader.

You left out:
- Provide a defensive layer around your framework AND use assertions inside
your code to protect yourself against bugs or unexpected situations.
--
Mark Rafn    dagon@dagon.net    <http://www.dagon.net/>


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2009 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.