4 ms·
The first form called the "open if statement" and the second the "closed if statement". The "open" variant is problematic once you have the "else" clause in th
by nivertech 4y ago
The first form called the "open if statement" and the second the "closed if statement".
The "open" variant is problematic once you have the "else" clause in the nested if statements, i.e. it becomes unclear to which "if" each "else" belongs, so the languages had to introduce some complex rules. With the "closed" form everything is straightforward and you don't have this problem.
The workaround in C-style languages (C/C++/Java/JS/TS/etc.) is to always put the else clause into the curly brackets, even if it's a single statement. Just to be sure put always both "then" and "else" branches into a curly brackets.
It can get even more complicated if you allow "if"-s as ternary operator inside the conditional expressions...
Another solution is merging "else if" into an "elif" keyword.
So just use "if-then-else-fi" / "if-then-else-end" with an optional "elif".
- pmontra 4y agoRuby's solution: if cond if cond something else something_else end end That else belongs to the second (closest) if even if I misindent the code like that. Of course Ruby doesn't care about indentation.
- nivertech 4y agoRuby uses closed form - which is a good design, but it doesn't have a separator between the condition and the "then" clause - which is IMO bad. I don't remember whether Ruby's if statement implemented using implicit blocks ...