I generally prefer if (var)
or if ($var)
if var
is used as a boolean, even if there isn't any such type in the language.
I very much dislike constructs like if (!strcmp(...))
or if (var == true)
. The first tries to be too smart, the second too dumb -- although it scales well to if ((var == true) == true)
, ... ;-)
Some languages, like Perl and C++, provide extra or even user defined interpretations of trueness. If the conversion to a boolean seems too magic, remember it's basically just an is_true(var)
or var.booleanValue()
, or something like that behind the scene, just a more concise syntax.
Related to your question, I like to formulate conditions in a positive way. Instead of
if (!condition) {
g();
}
else {
f();
}
I prefer
if (condition) {
f();
}
else {
g();
}
Even if there is only a single branch, and the condition is not terribly simple. (An indication for that is the need for a comment.) For example, instead of
// explain reason for condition here
if (!condition) {
f();
}
I prefer to phrase it as
if (condition) {
// explain condition here
}
else {
f();
}