Return Values
In #phpc we recently had a discussion about function return values; specifically from database queries.
I’m going to go on a (admittedly, rather sturdy looking) limb and say this applies to pretty much any function that returns from a data resource, not just a database .
My preference, is to return false only for error conditions, or when a function is supposed to only return one result (i.e. when selecting on a primary key) and fails to find any result.
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.
There is a simply solution though, an empty array, also evaluates as false.
[php]
function getData()
{
if (error()) {
return false;
} elseif (noData()) {
return array();
} else {
return myData();
}
}
if (!$data = getData()) {
foreach ($data as $row) {
// Show data
}
} else {
echo “No data found.”;
}
// or
$data = getData();
if ($data === false) {
myLog(“Something Bad Happened!”);
}
if (!$data) {
echo “No data found.”;
} else {
// iterate
}
[/php]
This gives the best of both worlds IMO — the ability to distinguish error conditions or not depending on if you need to in the given context.
- Davey
P.S.
This might be the start of a series of thoughts on common API best practices
BAM! I just unlocked the White Hat cap on @mojolive! http://t.co/GWVUht8R
@dshafik [2 weeks ago]
@rdohms @weierophinney especially here in Florida.
@dshafik [2 weeks ago]
@Arkantoze yeah, but NOT RIGHT OUTSIDE THE FRIGGEN DOOR
@dshafik [2 weeks ago]
@dshafik cool looking spider web!
@Arkantoze [2 weeks ago]
@dshafik Very pretty… and remember, spiders eat other insects…
@weierophinney [2 weeks ago]
















