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
possible.

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).

See http://c2.com/cgi/wiki?NullObject

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.

IMHO -

 - A

-- 
Alex Chaffee                               mailto:[EMAIL PROTECTED]
Purple Technology - Code and Consulting    http://www.purpletech.com/
jGuru - Java News and FAQs                 http://www.jguru.com/alex/
Gamelan - the Original Java site           http://www.gamelan.com/
Stinky - Art and Angst                     http://www.stinky.com/

---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to