|
Re: "if without an else" return value
|
Posted: Jun 19, 2008 12:20 AM
|
|
> One of the confusing things about an if without else > is: > if (true) > if (false) > println("yes") > else println("no")
> will print "no" where you would think it would print > nothing. Maybe this is something to avoid?
Well, perhaps it is confusing for someone thinking in Python style, as he would expect the 'else' to belong to the first 'if' only due to indentation.
As a Java coder, reading that example immediately "wrong indentation" popped up in mind instead of "unexpected result".
This is in the same category of error like:
assert(50 == 7 + 3 * 5)
The rule of innermost relation of if-else is as "suprising" as the rules for operator precedence. And as with setting parens in the arithmetic expression above, the right way to express the intented deflexion from the rule is indeed:
if (true) { if (false) println("yes") } else println("no")
Has more to do with code style. That leads to company style guides รก la : "always use braces" - even if it produces more optical noise.
Only one example for formatting, not Java standard, but expressive:
if (true) { if (false) { println ("yes") } } else { println ("no") }
|
|