Вопрос

If I have

return recordsAffected > 0;

which would return either true or false, do I need to put return recordsAffected > 0 ? true : false?

Это было полезно?

Решение

No, you do not have to as your code works just fine. You may find some developers recommend doing it because it is clearer to read and understand but that's a matter of personal opinion.

Always code as if the person maintaining your code is a violent psychopath who knows where you live - Martin Golding

Другие советы

You do not need that. Main reason, is that it would be 2 operations instead of one: first for comparison, second for value choosing. I also want to mention, that each conditional operator (even ternary) affects performance.

Short test:

<?php
header('Content-Type: text/plain; charset=utf-8');

$start  = microtime(true);

for($i = 1; $j = 1, $i <= 10000000; $i++){
    ($i == $j);
}

$end    = microtime(true);

echo 'Not ternary: ', $end - $start, PHP_EOL;

$start  = microtime(true);

for($i = 1; $j = 1, $i <= 10000000; $i++){
    ($i == $j ? true : false);
}

$end    = microtime(true);

echo 'Ternary: ', $end - $start, PHP_EOL;
?>

An it's results.

You certainly do not need to. The intention and semantics of

return recordsAffected > 0;

is perfectly clear. This should hold true for every decent programmer reading your code.

return recordsAffected > 0 ? true : false;

is redundant at best, but I'd go further and call it detrimental. The second snippet does not add anything to the statement but complexity. I'll bet if you did not write code like this all the time (and I believe most decent progammers don't) the second statement will take you at least two passes to grasp the meaning, if not more. When there are two semantically equal solutions you should always stick to the clearest one, which is not necessarily the most explicit one. Nobody would ever write something like

if(recordsAffected > 0 ? true : false)
{
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top