At
DCPHP, I saw
several clever presentations about unit testing, which essentially reinforced what I already know: if I could go back in time and actually guide the development of the CMS we had built in-house, I'd structure it not to have clever self-references and three-level inheritance...which would, incidentally, make it something less than a three-year project to create unit tests for it.
But over the years, with many beginning developers coming through our doors, I've seen several things that the guys who advocate unit testing assume you, as a sane person, are doing...but mostly I've seen those things not being done. So here's an easy one:
<?php
$sql = "SELECT id, name, type FROM people LIMIT 10 ORDER BY date_added DESC";
$result = mysql_query($sql);
if (mysql_num_rows($result))
{
// do stuff
}
?>
Great, eh? Checking to see if there are actually rows returned before you do something, right?
But what if your query fails? Remember, you write code not just for right now, but for when you do things down the line. Just like you make unit tests to catch any screwups before you go to production, you can be testing any calls right inside your code. So later, when you add "just a quick fix" and screw up the query, it doesn't have to fail if, for example, it only fails when you pass a variable in and the tests you wrote originally don't cover that.
So always be paranoid about any queries you make:
<?php
$sql = "SELECT id, name, type FROM people LIMIT 10 ORDER BY date_added DESC";
$result = mysql_query($sql);
if (false === $result)
{
// handle gracefully
}
elseif (0 < mysql_num_rows($result))
{
// do something
}
else
{
// handle the case of no data
}
?>
Obviously, in the world of PHP 5 and OO, you should be using exceptions and try-catch, but it is amazing to me the number of developers who will blithely assume their queries are perfect and will remain so, and that there's no risk they'll ever see a production box. Testing is one of the first thing a schedule- or budget-pressed project will skimp on when resources go short. Most clients react less well to "we had to cut your feature, because the budget is running low" than "no problem with your feature, we'll just do some spot checks instead of the full-on testing process." That is, they will until you screw up and they discover a page is completely unusuable on a weekend when you're off paddling down a river.
So write fault-tolerant code. Make sure that even if your query fails, you handle it in a graceful way--and that you provide yourself enough information to quickly figure out what's going on on Monday and fix the thing.