The Artima Developer Community
Sponsored Link

Condition check or exception?

Advertisement

Advertisement

This page contains an archived post to the Design Forum (formerly called the Flexible Java Forum) made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.

Message:

Condition check or exception?

Posted by Mike Mannion on 09 Jul 1998, 12:51 AM

> Say, I have a class MyClass which function (doit1() or doit2())
> is more efficient?
>
>class MyClass {
> MyObject myObj;
> ...
> ...
> void doit1() {
> if(myObj == null) {
> myObj = new MyObject();
> }
> myObj.process();
> }
> void doit2() {
> try {
> myObj.process();
> }
> catch(NullPointerException e) {
> myObj = new MyObject();
> myObj.process();
> }
> }
> }

Absolutely no question: doIt1() is more efficient. There are many more bytecode and stack operations involved in exception handling than in simple condition checks.

On the whole, exceptions should *never* be used as a replacement for normal flow of control.
If it is reasonable that myObj is null (as typically happens in "first time" invocation situations) then use a conditional statement to test for it.

Some special circumstances may require us to break this rule: If we've been given an API which does not provide a means for checking that some condition holds, then it may only be possible to invoke a method in which a thrown an exception is the only indication of failure.
However, a good API will provide a means to query, as in:

class MyClient
{
void someMethod()
{ if (aSupplier.canDoIt())
{ aSupplier.doIt();
}
else
{ System.out.println("Can't do it");
}
}
}

class Supplier
{
boolean canDoIt() {...}

void doIt() {...}
}

An arguably inferior variation of this would be:

class MyClient
{
void someMethod()
{ try
{ // No means to query supplier, so must use try..catch
aSupplier.doIt();
}
catch (CannotDoItException coe)
{ System.out.println("Can't do it");
}
}
}

class Supplier
{
void doIt()
{ if
throw new CannotDoItException();
...
}
}

Again, this all relates closely to the design paradigm "Design by Contract".
In DBC, one says that clients should always have a means to query supplier objects as to whether or not preconditions for a particular method are satisfied.
If conditions are not met, clients just shouldn't invoke the method. If they do, the supplier should have no bad feelings about throwing an exception back at the client. After all, this indicates misuse of a supplier's services (think "unchecked exception").
If conditions are met, clients can feel condifident that the supplier can carry out the task.

MM



Replies:

Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us