Re: Question on Effective Java Item 27



hforco@xxxxxxxxxxxxxx wrote:
In Joshua Bloch's Effective Java, Item 27 ("Return zero-length arrays,
not nulls"), he concludes with the following words:

"In summary, there is no reason ever to return null from an
array-valued method instead of returning a zero-length array."

I'm not convinced this is correct.

For example, let's say I have a look-up method for some data:

byte[] findData(Object key);

Surely in this case a zero-length returned value could be meaningful in
itself, and so in this case we should return either null, or throw an
exception, if an invalid key was used.

Any thoughts?


With Joshua's approach (which I do myself) I can do:

byte[] bytes = getBytes();

for ( int index = 0; index < bytes.length; index++ ) {
System.out.println(bytes[index]);
}


Where as with your null approach I have to :


byte[] bytes = getBytes();

if ( bytes != null) {
for ( int index = 0; index < bytes.length; index++ ) {
System.out.println(bytes[index]);
}
}

Or worst still, with the exception throwing one:


try{
byte[] bytes = getBytes();

for ( int index = 0; index < bytes.length; index++ ) {
System.out.println(bytes[index]);
}
}catch(NoBytesAvailableException e) {
// Not interested as there are no Bytes
}


Besides which, it would be very strange (IMHO) if an exception was thrown in this case - as an empty collection is rarely an exceptional case.

As for any issues you may have above memory or speed because of the empty array thats created - dont worry about - our apps always have bigger issues else where than empty arrays being created.

HTH

Andrew
.



Relevant Pages