Let’s just get one thing straight here people, an object that is null does not mean the same thing as a collection/array of length zero. I’m sort of seeing this more and more as I continue my existence on this planet and I say we put a stop to this now. Take this example method declaration (written in Java):
public Collection<searchresult> getSearchResults(String searchTerm);
Straight forward enough, I would hope. This method takes in a searchTerm String, magic happens (ah abstraction), and a Collection of type SearchResult is returned. Now here is the kicker: what happens if the search query resulted in no results? What should be returned? And why?
At this point, we essentially have two options if we want to successfully return from this method without using exceptions: return null or return a Collection of type SearchResult of size n | n >= 0;
When returning a Collection, the size indicates how many SearchResults there were. If someone were to search for “cows” and the Collection contained 23 SearchResult objects, then we should say that the search had 23 results. Contrary to that, if there are 0 SearchResult objects then we can say that the search had no results.
When null is returned instead of a Collection, that can only mean that something has gone wrong. For instance, the search could not be completed for any reason. This should be the only reason a null should be returned.
By returning a null if a search has been successfully completed, even if there are no results, tells the caller that there may have been an error, which is not what you want to communicate. Returning null should be the worst case scenario in a circumstance like this. It is the duty of the implementer of the getSearchResults method to fully communicate the actual status of things by returning what is the most correct in any situation.
Please do not return null lightly.