-2

I see most code-bases using bracketed if-statements in all cases including cases in which only one statement needs to be executed after the if.

Are there any clear benefits to always using bracketed if-statements or has it just become a standard over time?

What is the general consensus on this, would it be a big mistake to allow one-line ifs through our linter?

John Pizzo
  • 327
  • 1
  • 5
  • 9

2 Answers2

1

Largely this comes down to developer preference, although many reasons are given for using the curly braces on every control block.

First, it makes the control block more readable. Consider:

    if (some_condition)
runSomeFunction();
        runSomeOtherFunction();

Since indentation is not respected in most curly brace languages, this will work, but it really reduces the readability (only runSomeFunction() will happen in the control block). Compare to:

if (some_condition) {
    runSomeFunction();
}
runSomeOtherFunction();

Second, when you need to add something to the control block (which almost invariably happens more often than not), adding the curly's can be frustrating or easily forgotten leading to issues like the above.

Still, those largely come down to preference and you can always find exceptions (like if (some_condition) runSomeFunction(); which is much more readable than the first example above while still accomplishing the same goal in a much more concise format that retains readability).

cardonator
  • 386
  • 2
  • 9
0

If you have to go back to the code to add something, you might forget that you didn't open brackets, and your code wouldn't work if you exceed one line.

Other than that it's a matter of preference and format.

andrralv
  • 810
  • 7
  • 18