Willfull Ignorance

Sometimes, writing good code is really hard. But other times, writing good code is so darn easy you shouldn’t even have to think about it. In fact, it shouldn’t even be called “good code” — in these cases there should never be anything else, so we’ll just call it “code”.

For instance, if I see another line of code that does this:

$foo = isset($foo) ? $foo : 'default value';

I think I’ll kill someone.

Let me clear something up for you: using the ternary operator does not make you cool. However, assigning a variable to itself makes you very uncool.

if (!isset($foo)) $foo = 'default value';

Now why is that so hard to write?

2 Comments so far

  1. Matt on July 10th, 2008

    Maybe the programmer was trying to win points for using obscure procedures? Even in cases where the ternary syntax would be appropriate, I tend to just use an…

    if($x) {
    something();
    else {
    something_else();
    }

    It seems so much easier to read. Sure, you could do it in less code, but even a Programming 101 student would understand my code.

    Even as someone who’s been certified* in the use of ternary operators, I have to stop and think about the syntax of the sample code block you mention and what they’re doing. And this one is just asking for trouble? “Wait… If $foo is set, set $foo to $foo? I must be reading this backwards… But wait, then it’s setting an _undefined_ variable to itself, which makes even less sense…”

    * Bald-faced lie

  2. Matt on July 10th, 2008

    Hey, I didn’t get an e-mail bounce when I left a comment! Yay! 😀

Leave a Reply