commons-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Alex Chaffee / Purple Technology <>
Subject Re: [general] throw exception OR return value
Date Wed, 12 Mar 2003 23:39:16 GMT

On Wed, Mar 12, 2003 at 11:23:57PM +0000, John Keyes wrote:
> If I have an instance that implements an interface, but does not need
> to implement all of the methods, is it better to return a value or
> throw an exception.

Without knowing any other details, I think it's safer to throw a
runtime exception.  Otherwise the null may propagate to some other
part of the code, and when that other code throws a NullPointer, then
it'll be harder to track down why.  In other words, calling an
unimplemented method is a violation of the contract, and indicates a
programmer error, so the code should fail as quickly and as loudly as

OTOH, if the new subclass is intended to be used panmictically with
other polymorphic equivalents, then it may make sense to have it
return a meaningful, but hardcoded value.  If the method returns a
primitive, this value could be zero (shed.getGarageSize() -> 0); if it
returns an object, then it could be a Null Object that, in turn,
returns hardcoded zero values (shed.getGarage().getSize() -> 0).


This does, of course, hide the contract violation I mentioned in the
first paragraph, so use with care.

In no case should a method specced to return a reference to a valid
object suddenly start returning null.  Null as a return value
sometimes has meaning (e.g. in Java collections, where it means "no
such element"), but if that meaning were not specified by the
*original* superclass or interface, then a rogue subclass shouldn't
start bending the semantics by returning null.


 - A

Alex Chaffee                     
Purple Technology - Code and Consulting
jGuru - Java News and FAQs       
Gamelan - the Original Java site 
Stinky - Art and Angst           

To unsubscribe, e-mail:
For additional commands, e-mail:

View raw message