Article 6CA9N CodeSOD: Underscoring the Importance of Good Naming

CodeSOD: Underscoring the Importance of Good Naming

by
Remy Porter
from The Daily WTF on (#6CA9N)

An eternal problem in programming is "empty strings are basically nulls, right?" Frequently, when someone hands us "", we know that represents "no value", and thus is basically null. Well, sometimes. Other times it's not. Tracking this chaos is a common source of bugs and WTFs.

Martin's team had a problem in PHP. See, the is_null function is, well, checking for nulls. It isn't checking for empty strings. Being PHP, the empty function also doesn't check for empty strings, it checks for strings that can coerce to false (which includes the empty string, but also includes '0'). The "best" way in PHP to check for empty strings is just a direct comparison- $val == ''.

That's awkward, so it's really good one of Martin's co-workers implemented a function that makes that easier to read:

function isnull($val1) { return (is_null($val1) || ($val1 == ''));}

Yes, they named their isNullOrEmpty function isnull, while the default built in one is named is_null. And I'm sure you'll be shocked to learn that this caused no end of confusion in their codebase, with isnull and is_null being used roughly interchangeably where they worked, and not being used where they didn't work, or even better, the confusion leading to lines like:

if (isnull($myvar) || $myvar == '')...

This isn't necessary if you're using isnull but it is if you're using is_null, but skimming through the code without knowing you need to watch for that underscore is going to confuse a lot of people.

buildmaster-icon.png [Advertisement] BuildMaster allows you to create a self-service release management platform that allows different teams to manage their applications. Explore how!
External Content
Source RSS or Atom Feed
Feed Location http://syndication.thedailywtf.com/TheDailyWtf
Feed Title The Daily WTF
Feed Link http://thedailywtf.com/
Reply 0 comments