Hacker News new | ask | show | jobs
by Merovius 2745 days ago
> Allowing single line if statements (as, eg, ruby does) also allows for clearer code, at the expense of consistency.

This (or rather allowing conditionals without braces) was what I was referring to. They are a foot-gun, because of the lack of clarity. It's a common source of bugs in C/C++ code that a developer thought they'd add a line of code to a conditional block or loop but didn't, because of a lack of braces. Requiring braces unconditionally make it always unambiguous and obvious what block a given statement belongs to.

Obviously YMMV - this is, as most discussions in programming, a matter of opinion. Which was my point :)

1 comments

I'm aware of the reasoning. As you say, in C people would carelessly edit:

    if (condition)
      doSomething
to

    if (condition)
      doSomething
      doSomething2
So fair enough, you protect against that. You cannot therefore conclude that:

    if (condition) {
      doSomething
    }
is clearer or that 1 line if statements aren't clear. First of all, you've purchased your insurance at the cost of brevity. Which is quite a high price, especially when you have to use them constantly to write:

    if err != nil {
      return err
    }
and when it forces all of your 1 line conditional expressions to be 4 - 6 lines, per my OP.

And there are solutions that allow you to buy your insurance without such a high price. You can invert the position of the if, as ruby does. You could make a rule that when you don't have braces you have to write your statement on the same line. The point is this isn't the only way out. And clarity is not the same as preventing one specific kind of error, which occurs only in a context which could be changed as well.

on that note: here's an example of a very costly example of this exact mistake, Apple's famous "GoTo Fail" for anyone that isn't aware of it: https://dwheeler.com/essays/apple-goto-fail.html