According the "Practical Java" (a great book by Peter Haggar), the
developer is on logically solid ground.  In fact, "Praxis 26" is titled
"Throw exceptions from constructors."

A quick paraphrase:

Constructors cannot return error codes.  Presuming you want to ensure that
only "valid" objects can be constructed, consider the alternatives to
throwing exceptions from the constructor:

One alternative is what Haggar calls "two-stage construction."  Pieces of
the construction process that can cause errors are moved into a separate
routine.  The user constructs an instance, then calls the "finishing"
routine and checks the return code or exception from that secondary
routine.  Yuk.

Another alternative is having an "i_am_validly_constructed" flag in every
object.  Either the user checks the flag before every (or at least the
first) method call, or each instance method internally checks the flag as
the method is entered (Yuk times Yuk).

Neither of these is as simple and robust as simply throwing exceptions
directly from the constructor.

Sure, in simple cases the argument is often made that "the poor class user
has to wrap all his constructor calls with try/catch," but that isn't
necessarily so.  If the constructor throws exceptions that are subclasses
of java.lang.RuntimeException, no try/catch wrapping is required.  That's
why "IllegalArgumentException" or "UnsupportedOperationException" (or even
"NullPointerException") make nice candidates to be thrown from
constructors.

Just my $0.02 added to Haggar's $64K.

On Thursday, 10/03/2002 at 08:14 MST, "Repine, Burt" <[EMAIL PROTECTED]>
wrote:
> A developer on our team just introduced a new set of classes the project
> that throw an exception from the constructor.
> The classes follow the Value Object pattern so they're just data
containers.
> The exception is thrown if a null value is passed in.
>
> This seems like a really bad idea to me with no inherent benefit but the
> developer is holding fast to his implementation.
> Are there any philosophies out there on this subject?

-blair



____________________________________________________
To change your JDJList options, please visit:
http://www.sys-con.com/java/list.cfm

Be respectful! Clean up your posts before replying
____________________________________________________

Reply via email to