Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Q&A

Welcome to Software Development on Codidact!

Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.

Comments on Is omitting braces for single statements bad practice?

Parent

Is omitting braces for single statements bad practice?

+9
−4

Consider this code:

while(arr[index] != 0)
    index++;

vs

while(arr[index] != 0) {
    index++;
}

Personally, I prefer the first. The fact that the braces are not needed makes them -- unnecessary. :)

To me, it's just clutter that wastes a line. Or 2 if you're one of them that also want the opening brace on a new line. The line waste can be avoided though, if you do like this:

while(arr[index] != 0) index++;

I often do that, and I like the style. Partially because it makes those loops stand out from loops with braces.

One argument I've heard for always using braces is that if you want to add another statement, then you need to remember adding braces or you will have bugs that can be hard to find. For instance, this would be an endless loop:

while(arr[index] != 0) 
    println("No zero found");
    index++;

While this is technically true that this mistake can be done, I find it a bit meh as an argument. If you're using an editor that autoindents the code, this mistake would be spotted immediately. And since using such an editor is something that you should do anyway, the point of this argument is a bit moot.

Plus, even though I have often coded without such an editor, I cannot remember ever doing that mistake. It feels like a mistake that one could do if you're used to Python. But adjusting coding standards of C, C++, Java and such to not confuse Python coders does not really seem like the right path to go.

Apart from this argument, I have not really seen anything else than the consistency argument. That always using the same style is consistent. Well it's true, but consistency is not ALWAYS good.

Have I missed something here? What do you say? Is omitting braces for single statements bad practice?

History
Why does this post require attention from curators or moderators?
You might want to add some details to your flag.
Why should this post be closed?

2 comment threads

Put the `{` on the next line and you wouldn't waste any lines. (1 comment)
General comments (5 comments)
Post
+15
−0

While [the Apple "goto fail bug"] is pretty interesting, it's anecdotal evidence. I understand that it's still possible to produce bugs like this. One could also reasonably argue that it could have been avoided if they used else if instead of if or didn't use goto.

Aviation safety is built, pretty much completely, on that kind of "anecdotal evidence"; and, on the whole, it's pretty successful (it's part of why virtually every airliner accident makes headlines, but very few car accidents do, even though in aggregate, far more people die in car accidents than in airliner accidents). So are many other safety regulations. Basically, when something goes wrong, a bunch of very smart people sit down and try to figure out what went wrong, what allowed it to go wrong, and what change to the existing regulations or practices would have prevented it from going wrong.

I can't help but notice that, in your example, you suggest that

while(arr[index] != 0) {
    index++;
}

should be shortened to

while(arr[index] != 0)
    index++;

because the compound statement delimeters are "unnecessary". But you don't take the obvious next step and suggest to instead write

while(arr[index++] != 0);

which will save you yet another line. It also saves you from, completely unnecessarily, naming the iterator variable separately on that second line. Why not?

I'll hazard a guess: because that will trip people up. It's perfectly valid code. It'll accomplish the same thing. It'll almost certainly have the same side effects in all of C, C++ and Java. And because people aren't used to that kind of construct, at a minimum, it will require expending additional effort to parse. Just because it's valid doesn't make it good.

Yes, in an ideal world, people wouldn't make mistakes, and everyone would do exactly what they intended to do and nothing else. Unfortunately, we don't live in that world, nor do I think we are likely to inhabit any world like it any time soon. If we accept this, it stands to reason that we should look at what can be done to reduce the likelihood of mistakes.

And let's face it, it's a lot harder to accidentally add a statement to the wrong level if every level is laid out with curly braces, begin/end, or whichever other construct the particular language uses to combine statements into compound statements. It's far easier to accidentally (and without noticing it afterward) go from

if (x)
    y();
z();

to

if (x)
    y();
    y2();
z();

than from

if (x)
{
    y();
}
z();

to

if (x)
{
    y();
}
    y2();
z();

when you meant to make both the y() and y2() calls conditioned on x. No matter what tooling you're using, that last example immediately stands out as "it just looks plain wrong", whereas the variant without the curly braces doesn't. Likewise, if you were to write

if (x)
{
    y();
}
y2();
z();

(correct indentation, but the y2() call placed in the wrong spot) it is also immediately clear that the call to y2() is not conditioned on x, even though that was the original intent.

If we can make syntactically valid but semantically wrong code actually look wrong, it greatly reduces the risk of semantically wrong code slipping through the cracks. The compiler will already catch things that are syntactically wrong, but it can't catch those things where what the programmer wrote is valid, just not what was intended.

Indeed, this "costs" a few extra lines for the braces (or equivalent keywords in languages that don't derive basic syntactical elements from B, such as for example Python or SQL). But if your code is so deeply nested, with so many separate short snippets, that this is actually a problem, maybe you should consider refactoring it anyway. Individual preferences aside, it's not like we're still using VT52 terminals as our primary display devices.

History
Why does this post require attention from curators or moderators?
You might want to add some details to your flag.

1 comment thread

General comments (9 comments)
General comments
klutt‭ wrote about 4 years ago

Yes, I could write it as a oneliner, but don't get stuck on the specific example. It was just made as an example, and actually, I would have written it as a oneliner, but I would do it by just removing the newline and have while(arr[index]) index++; as a single line. Actually I'm pretty fond of doing that for single statement blocks.

Lundin‭ wrote about 4 years ago

"Aviation safety is built, pretty much completely, on that kind of "anecdotal evidence"" Well, not really. Rather a group of experts getting together and agreeing on how things should be done. If you can quote for example DO-178, then that's a well-respected standard and canonical source.

Martin Bonner‭ wrote almost 4 years ago

Err, Python is the counter example to this question. You don't add the braces because the indentation is semantically significant.

Canina‭ wrote almost 4 years ago

@MartinBonner Since Python to my knowledge doesn't use braces at all to delimit block/compound statements, I think it's a somewhat irrelevant example to a question about brace styles. Note that the question was originally (and still was when I originally posted this answer) tagged c, c++, java, so clearly focused on C-like languages.

Canina‭ wrote almost 4 years ago

@Lundin I very strongly suspect that even the "experts ... agreeing on how things should be done" is based on experience regarding what has worked historically to reduce failures. I also don't know about DO-178 specifically, but a lot of at least aviation safety standards is more about what to accomplish (for example: system X must have a failure rate of less than once per Y hours), not about how to accomplish that goal, which is then much more up to the manufacturer to decide.

Canina‭ wrote almost 4 years ago

More to the point regarding aviation safety, look at just about any accident report; it'll list some number of recommendations that would have served to prevent the accident had they been in place, and are made as recommendations because the accident investigators believe that having them in place will reduce the risk of a recurrence of the accident; either specifically, or, even better, a whole class of accidents. (Consider crew rest requirements versus fatigue-related accidents.)

Lundin‭ wrote almost 4 years ago

@Canina Yeah well, mainly "anecdotal" was a just a poor wording, "empirical evidence" is another thing entirely. That is, "I heard it from a guy on the internet" vs "I made field population studies of x cases".

Lundin‭ wrote almost 4 years ago

As for safety standards, the good ones focus on "what should we do when this error occurs" rather than "error must not happen". Of course you should prevent errors from happening, but you also need to have a plan of what to do when they happen anyway. This is where defensive programming saves the day - as long as you can detect errors that shouldn't be happening, you can usually revert to a safe mode as best as you are able.

Peter Taylor‭ wrote over 3 years ago

while(arr[index++] != 0); does not accomplish the same thing, because it increments index one more time than while(arr[index] != 0) index++;