Re: Question on Effective Java Item 27



S Perryman wrote:
if an invalid key was used.

Is this different to a key that is valid, but doesn't match anything ??


Sorry, no ...by 'invalid key' I meant one that doesn't match anything.


This is a common problem, specifically that one is attempting to use one
value to convey multiple meanings. So either :

1. define multiple parameters, one to retrieve the outcome of the search,
and the other for the value.

By 'multiple parameters' do you mean multiple methods - or are you
refering to 'out' parameters? Java doesn't have out parameters.

2. define a result type that holds both parameters

An example of 2 is :

class FDResult
{
boolean found ;
byte[] value ;
}

FDResult findData(Object key)
// post : RESULT.found XOR (RESULT.value == null)


Regards,
Steven Perryman

I like this ... particularly as using the two-method approach
(isExistingKey, followed by getValue) would mean that look-up of the
key is done twice.

Although I appreciate that this is more explicit than using a null
return value, do you not agree that as long as it was documented that
null return value meant the key was not found, that it would still work
in the same way?

There is nothing fundamentally different between the following:

byte[] value = findData(key);

if (value == null) {
// key not found ....
} else {
// do something with value
}

and this ....

FDResult result = findData(key);

if (result.found) {
byte[] value = result.value;
// do something with value
} else {
// key not found
}

.... other than the fact that the second example is much clearer. It's
in this sense that I meant Bloch was wrong in saying that there is
never a reason to return null. Perhaps "there are cases where it is
meaningful to return null, but in all those cases there are other
approaches which are more explicit and therefore preferable" would have
better.

.