HACKER Q&A
📣 melissalobos

Forget tabs vs. spaces, what about braces around single line statements?


Everyone knows that programmers tend to have strong opinions about minor technical details. Silicon Valley enshrined this with tabs vs. spaces. But Emacs vs. Vim is older. For me, my personal pet peeve is in curly braced code not having braces around single statements. Compare:

No brace

if(x) doStuff(x);

Versus

if(x){ doStuff(x); }

One objective point in my favor is that you avoid issues with misleading indentation and a few cases that have caused CVE's. Not in my favor, the first is shorter. And people often believe code density is a virtue.

I never really thought about this a being a huge issue, until recently I had an interviewee express a strong preference for no braces, and I thought it was absurd to feel so strongly, and secondarily I thought they were wrong.

Anyone else have strong feelings either way that want to express themselves?


  👤 techdragon Accepted Answer ✓
The only strong feeling I have here, is that where it exists in a language it shouldn't be optional.

"Optional syntax" is potentially confusing syntax. One of the nice things about code formatters like Black, rust-fmt and gofmt is that they say "do it this way" with respect to potentially optional syntax like this exact brace/no-brace issue. I primarily work in Python, so i don't write a lot of "braced" code like this, but where I do, in languages like C# and so on, I'll always use the braces, its just clearer. I'm sticking to the explicit is better than implicit rule thats served me so so well over the years. I do it with braces, i even do it with imports, I'm that weird person off in the corner writing C# that uses fully qualified names instead of doing module imports, I cant stand the overly implicit behaviour of the imports in dotNet. Explicit wins for me every time ( Except for writing my own SQL ;-) )


👤 quantified
Put the if() and doStuff() on separate lines too

👤 TowerTall
The famous bug "GOTO FAIL" happened because of no curly brackets

https://nakedsecurity.sophos.com/2014/02/24/anatomy-of-a-got...


👤 simonblack
Always.

Today, there might only be a single statement line following that conditional. Tomorrow there might be three or more.

That's a perfect opportunity for a single conditional line, followed by two unconditional lines.

And the next programmer that has to track down that bug will come after you with a disembowelling knife.


👤 beardyw
I think there are some cases where code is clearer if a single line suffices, but for an extra 2 characters curly braces avoid misunderstandings.

👤 emptyparadise
Some languages don't let you skip the braces.