There are certain things which you see in code that, at first glance, if you haven’t already learned better, look like they might almost be clever. One of those in any construct that starts with:

switch(true) {…}

It seems tempting at various points. Your cases can be boolean conditions now, but you can also collapse cases together, getting tricky with breaks to build complex logic. It’s more compact than a chain of ifs. It’s also almost always the wrong thing to do.

Kasha stumbled across this while tracking down a bug:

    // The variable names in this code have been anonymized to protect the guilty. In the original they were actually ok.
    private function foo($a, $b)
        switch (true){
            case ($a&&$b): return 'b';
            case (!$a&&!$b): return 'c';
            case $a: return 'a';
            casedefault: return 'unknown';

As Kasha’s comment tells us, we won’t judge by the variable names in use here. Even so, the awkward switch also contains awkward logic, and seems designed for unreadability. It’s not the most challenging logic to trace. Even Kasha writes “I comprehended the piece just fine at first while looking at it, and only later it hit me how awkward it is.” And that’s the real issue: it’s awkward. It’s not eye-bleedingly bad. It’s not cringe-worthy. It’s just the sort of thing that you see in your codebase and grumble about each time you see it.

And that’s the real WTF in this case. The developer responsible for the code produces a lot of this kind of code. They never use an if if they can compact it into a switch. They favor while(true) with breaks over sensible while loops.

And in this case, they left a crunch-induced typo which created the bug: casedefault is not part of the PHP switch syntax. Like most languages with a switch, the last condition should simply be default:.

[Advertisement] Continuously monitor your servers for configuration changes, and report when there's configuration drift. Get started with Otter today!