Useless use of if award

Similar to the useless use of cat award. The useless use of if award highlights code examples where people use the if function or ternary operator when the return of the expression does the exact same thing. I first noticed this with returning boolean values from php functions. To protect the innocent the winner of today’s award will remain anonymous.

<anonymous> to my knowledge, youll have to SUM(IF(your_field <> “”, 1, 0)) as total_non_empty

Ignoring that the whole query should be using where your_field != ” and group by the non if() way to write this is:

SUM(your_field <> ”)

These examples aren’t an award to a specific person since I’m digging them up from my memory. This pretty much applies to both C and PHP.

< ?php

function foo()

{

$str = 'foo';

return $str == 'foo' ? TRUE : FALSE;
}

?>

Can be written as

< ?php

function foo()

{

$str = 'foo';

return $str == 'foo';
}

?>

I hope this helps you save a few keystrokes when writing code in the future.

4 Comments

  1. Hm…

    I tried to optimize the function even more and after hard hours of profiling, I came up with:

    ;)

  2. WP snipped my function! :(

    function foo() {
    return true;
    }

  3. Jan Pieter Kunst says:

    I don’t like ‘saving keystrokes’ when writing code. That leads to the slippery slope of incomprehensible, write-only code. In fact, I never even use the ternary operator. I would write your PHP example like so:

    $str = ‘foo';

    if ($str == ‘foo’) {
    return TRUE;
    } else {
    return FALSE;
    }

    Uncool, isn’t it?

  4. Arno says:

    While the PHP example is a valid one, I don’t think that SUM(your_field ‘’) is a good one. It implies that a boolean type TRUE is always cast into an interger 1. Which is not always the case. I have seen boolean TRUE as 1, 255, -1, and just about any other 32bit value in different languages, versions, and compilers over time.

    Who says that MySQL (which I assume the SUM example was run on) does not change the boolean->int cast from 1->-1 in a next release?

Leave a Reply