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
@dshafik whoops! Thx! No glasses on!
@cloudsteph [1 hour ago]
@cloudsteph your first link is missing a letter (tumbLr) and goes to some spammy shit.
@dshafik [1 hour ago]
RT @lig: Ok #tek13 attendees - you are now home and have no excuse *NOT* to rate your speakers on Joind.in - http://t.co/QM0zBGE5tI
@dshafik [4 hours ago]
(correction, it's a @BlueMicrophones Yeti not @bluemics)
@dshafik [6 hours ago]
Probably the worst part about my new @bluemics Yeti mic is the irresistible urge to grab it and start belting out lounge music!
@dshafik [6 hours ago]
















