[rabbitmq-discuss] Java RabbitMQ API bug in response.getHeaders()?

Mario Leyton mleyton at niclabs.cl
Thu Oct 27 17:23:47 BST 2011


Thanks for your quick reply Tony but I completely disagree with your
implementation choice ;-)

If there are no headers, it doesn't matter why, a good API should always
return an empty Map o List and not null because it contaminates the API
user's code.  Instead of simply doing:

Map headers = response.getHeaders();
for(String k: headers.getKeys(){ ... }

The API user has to add the code:

if(headers != null){
   for(String k: headers.getKeys(){ ... }
}

This if(headers != null) has to be added by all API users, even if they
don't care to distinguish between the empty header or unsent header. If
an API user doesn't  add the if, the code actually breaks with a null
pointer exception depending on the message!

If the API user is actually concerned on why the set is empty you can
provide additional info like headerWasSent() to distinguish the
difference. This is actually a lot clearer for maintaining the API
user's code because it is evident that he is testing if the header was
sent or not instead of simply checking as not to through the
nullpointer  exception.

If you are still not convinced, I was convinced myself after reading
Joshua Bloch's Effective Java Programming:

http://java.sun.com/docs/books/effective/toc.html

Item 43: Return empty arrays or collections, not nulls

Mario Leyton
--
NIC Chile Research Labs


On 10/27/11 1:06 PM, Tony Garnock-Jones wrote:
> On 27 October 2011 10:41, Mario Leyton <mleyton at niclabs.cl> wrote:
>
>>  We are using rabbitmq java client and I believe the following is a bug:
>>
> Nope, it's deliberate. null, here, represents that no headers were sent.
> This is distinct from an empty map being sent. AMQP's basic properties
> structure includes "absent/present" bits for all of the fields; we chose to
> use "null" to represent "missing", as in this instance it is unambiguous.
> In languages like ML and Haskell we'd use 'whatever option and Maybe
> whatever, respectively. In C, we use a bitmap stored separately from the
> struct members concerned.
>
> So when reading (or writing!) basic properties in Java,
>
>    - null means "missing value" or "no value"
>    - empty map, empty string etc. is a *present* value but is otherwise
>    just itself
>    - non-empty maps, strings, etc are present values
>
> Regards,
>   Tony
>



More information about the rabbitmq-discuss mailing list