
- Image by cackhanded via Flickr
Davey Shafik discusses return values from functions. In the specific case of a function that returns values from a database, he wants to return false on error and an empty array if the data set is empty. He also has a reason for that:
“However, it’s very rare that I care about whether I hit an error condition or just got no result when it comes to display — more to the point, my user doesn’t care.”
That’s interesting, but I think that someone trying to understand the code might care. It might be easier to read if the two cases were somehow handled separately, at least at the lower levels.
What does help, as pointed out by several commentators, is to throw an exception instead of returning false. The book Clean Code recommends throwing exceptions instead of returning error codes. That gives you flexibility in handling the error. It can be handled at a higher level without having to clutter the levels in-between with error handling code.
In general, it’s often a good idea to return values that don’t require any special handling by the calling function. An empty array is an example. Foreach loops will happily do nothing, and everything runs smoothly, although you may need to check for emptiness at some point (typically to give a message such as “no records found).
Here are some general recommendations for handling return values in PHP. I’m sure they’re not perfect, but at least I can enumerate a number of alternatives.
- Data set. Return an array (empty if no data is returned). If the data set can be very large, return an SPL iterator that can be used interchangeably with an array in foreach statements. Or, if you have a good reason to do so, return some kind of data set object (Zend Framework does this).
- Error condition. Throw an exception. Or, if it’s not really an unexpected error, consider letting the calling code test for the error condition before calling the function in question.
- Single value. If you return a data structure as an associative array, it may be useful to return an empty one if nothing is found. Even more interesting is the Null Object pattern. If you would normally return a Contact object and the query returns nothing, return a NullContact object that has null operations and will return false if you call isNull() on it.
![Reblog this post [with Zemanta]](http://img.zemanta.com/reblog_a.png?x-id=4399ea86-a66f-42c9-b6d7-188948a0b51b)