My attempted better advice would be to keep methods short and the nesting/indentation limited. Use good method names. Make it easy to understand each method in isolation.
My attempted better advice would be to keep methods short and the nesting/indentation limited. Use good method names. Make it easy to understand each method in isolation.
Seriously are you saying that
if (x) {
return y;
} else {
return false;
}
is as easy to read as return x && y;Regarding which way is better, there's not much benefit arguing one way or the other. This is a leaf decision. It doesn't affect the structure of other parts of the code.
It's been in nearly all languages, and for decades before python existed.
>>> 0 and 'asdf'
False
>>> 3 and 'asdf'
'asdf'
>>> 3 and ''
''
'and' and 'or' in python are short-circuited as in e.g. C, but it's even more short-circuited! The "last" component is not evaluated in a boolean context. For a complete evaluation you have to use the expression in an if or while statement or apply the bool() function. I would say it's like a monad, if that helps. if isAdmin:
return false
if not isActive:
return false
return true
vs return (not isAdmin) and isActive if (a) return false;
if (!b) return false;
return true;
May be easier to read than: return !(a || !b); !a && b
? :) return a ? false : b;I’m a heavy user of ternary, but it’s still an “if”. And and Or are (not very much) higher-level operations.
a -> isAdmin
b -> isActive
const isDeletableUser = !isAdmin && isActive;
return isDeletableUser;
(Better would be naming the function "isDeletableUser" instead of the intermediate const, but was keeping with the original.)Point is for me that booleans with readable names shows how eliminating ifs becomes not only doable but arguably preferable.
<?php
$x = 1;$y = 2;
function test1($x, $y) {
if ($x) {
return $y;
} else {
return false;
}
}
function test2($x, $y) {
return $x && $y;
}
var_dump(test1($x,$y));
echo "\n";
var_dump(test2($x,$y));Since otherwise, it’s not a question of readability anymore. (But yes, incorrect transformations are incorrect.)