the corner office

a blog, by Colin Pretorius

« Tourist stuff | Main | Linkety link »

Return an empty collection, not null

I just got bitten by a silly thing: according to the J2EE spec, HttpServletRequest.getCookies() returns an array of cookies, or null if no cookies were sent with the request.

Why return null? It forces client code to explicitly check for null, while boiler plate cookie extraction code requires you to iterate through the list of cookies anyway. You could just as easily communicate 'no cookies' with an empty array, and it results in less crashable code.

True, common convention is to return null when you're unable to find an object that's supposed to be returned by a method - that's an understood and sensible convention. I don't think it follows that the same should be done when returning collections of objects. My preference is almost always to return an empty collection, as opposed to returning null. Why? You can still explicitly check for the existence of returned objects with a length == 0 or size() == 0 check, and iteration generally drops right though, with no NPEs and no NPE-avoidance code required.

The only argument against doing that might be performance - saving the creation of an object when no results were found. Apart from extreme cases - where the reasoning should be documented - empty results aren't the normal case and performance gains are likely to be infinitessimal, if they exist at all.

{2007.07.15 - 23:45}


tech blog


rssfeed posts

© Colin Pretorius