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.
July 21st, 2006 at 2:46 pm
Hm…
I tried to optimize the function even more and after hard hours of profiling, I came up with:
July 21st, 2006 at 2:48 pm
WP snipped my function!
function foo() {
return true;
}
July 21st, 2006 at 3:18 pm
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:
Uncool, isn’t it?
July 23rd, 2006 at 12:11 am
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?