By selikoff
via selikoff.net
Published: Oct 15 2008 / 09:06
Continuing on Jeanne’s theme of nulls, its a pet peeve of mine when I come across code that returns null arrays instead of empty arrays. The purpose of this post is to discuss some of the reasons why its a good practice to return empty arrays, including Collection objects or typed array.



Comments
eelmore replied ago:
Check for nulls in the code that consumes these things.
chudak replied ago:
I disagree. Always return an empty collection unless there is an error. The blog is spot on.
,
horza replied ago:
I disagree with the disagreement. I much prefer it when a code returns a NULL when there are no results as it is the current convention in all languages and libraries I have come across. Any error handling/exception is within the library/function itself and handled there. This then allows the syntactically easy boolean test. Though providing one item less information it still makes sense as error or no error there are still no results being returned and you have to deal with that. Also the last supposedly ambiguous example doesn't even make sense, as if convention dictates that either an empty set or an error sends back NULL you obviously do not need to test separately for the empty set. Overall I prefer consistency that will work across all code over a slightly superior technical solution which I have to remember is an exception and will become a gotchya for anybody that takes over my legacy code. If the revolution comes, and everybody including ISO/ANSI/etc dictates empty set for no results and null for errors then I will quite happily switch sides!
Phillip.
selikoff replied ago:
Consistency that will work across all code? You're one of those people that writes files in Java as you would in C++, with no standard functions, and all in byte code, right? Java affords some useful notions such as Collections.EMPTY_LIST, which have definite uses, not returning a null pointer is one of them.
Voters For This Link (33)
Voters Against This Link (0)