Coding Malpractice

I just wrote the following line of code. And it’s no mistake: it functions perfectly and does exactly what I wanted it to do:

$count += 0;

This is surely poor programming practice, essentially implicitly recasting a variable as an integer. But it’s simple and it works flawlessly. (The context: I run an SQL query saying SELECT SUM(votes)..., which makes the tabulation of all the entries MySQL’s problem, not mine. The one ‘flaw’ is that the sum of no votes isn’t 0, but NULL. This becomes a very important distinction when you’re trying to display a number: “0 votes” isn’t the same as ” votes.”)

Since we all know that NULL + 0 = 0 (and, of course, integer + 0 = integer), adding 0 works flawlessly. Could I just convert it to an integer? Probably. But I haven’t done that stuff in a while, and I was far too lazy to pull up the documentation. And incrementing a variable by 0 is way more fun.

One thought on “Coding Malpractice

  1. A few days ago I stumbled across something in one of our applications that was essentially:

    ...
    } else {
    $amount = $amount;
    }

    Which is essentially a non-op, except it actually does take an operation (or two?).

    By the way, PHP now supports very C-like casting; for instance:

    $count = (int)$count;

Leave a Reply

Your email address will not be published. Required fields are marked *