95

I've searched for this, but couldn't find an answer and for whatever reason I was too ashamed to ask professor, due to that feeling when hundreds of people stare at you...

Anyhow, my question is what's the importance of having brackets? Is it OK if I omit them? Example:

for (int i = 0; i < size; i++)  {
   a += b;
}

vs

for (int i = 0; i < size; i++)
   a += b;

I know both of them will work, but if I omit the brackets (which I tend to do a lot, due to visibility) will that change anything, anything at all? As I said, I know it works, I tested it dozen of times, but now some of my uni assignments are getting larger, and for some reason I have irrational fear that in the long run, this my cause some problems? Is there a reason to fear that?

skaffman
  • 398,947
  • 96
  • 818
  • 769
vedran
  • 2,167
  • 9
  • 29
  • 47
  • I always use a code formatter for readability as this solves many potential causes for confusion. This can make using curly brackets redundant – Peter Lawrey Nov 07 '18 at 19:53

16 Answers16

164

It won't change anything at all apart from the maintainability of your code. I've seen code like this:

for (int i = 0; i < size; i++)
   a += b;
   System.out.println("foo");

which means this:

for (int i = 0; i < size; i++)
   a += b;
System.out.println("foo");

... but which should have been this:

for (int i = 0; i < size; i++) {
   a += b;
   System.out.println("foo");
}

Personally I always include the brackets to reduce the possibility of confusion when reading or modifying the code.

The coding conventions at every company I've worked for have required this - which is not to say that some other companies don't have different conventions...

And just in case you think it would never make a difference: I had to fix a bug once which was pretty much equivalent to the code above. It was remarkably hard to spot... (admittedly this was years ago, before I'd started unit testing, which would no doubt have made it easier to diagnose).

tbodt
  • 16,609
  • 6
  • 58
  • 83
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Yes, I'm aware of that issue, I don't use brackets when there's just one line expected after if... – vedran Nov 05 '11 at 12:50
  • 14
    @vedran: So you're aware of the issue but you're just assuming it'll never bite you? And that everyone reading your code will know what to expect? I'm just saying - there's a reason why they're required in the coding conventions I've worked with :) – Jon Skeet Nov 05 '11 at 12:55
  • 12
    I just felt like a private being talked down to by a sarge. Yes, while it is more convenient for me, other from my group my find it annoying and problematic. I will make sure to use brackets everywhere from now on. – vedran Nov 05 '11 at 13:00
  • 1
    @vedran: Oh there's no reason why you *have* to take my advice - I'm just saying what I've found helpful in the past, and which my particular experience in industry has typically used as the convention. – Jon Skeet Nov 05 '11 at 13:10
  • 1
    One way to stick to a code style is by using [Checkstyle](http://checkstyle.sourceforge.net/), also as [Eclipse plugin](http://eclipse-cs.sourceforge.net/). One of the suggestions is to always use braces, I also always put them. However the issue is much mitigated, by using IDEs, such as Eclipse that can autoformat your code at every save. – stivlo Nov 05 '11 at 16:08
  • 14
    @vedran nice metaphor, except Jon Skeet is no sarge, he's the commander in chief :-) – stivlo Nov 05 '11 at 16:12
  • 6
    @stivlo Oh I'm sure his grace will pardon minor disobedience ;) Personally I do put brackets after statements, because it's part of every coding guide I've ever seen, but I think it's a pretty weak argument today. With automatic code formatting everywhere you should never see the code in its first form anyhow and if the indentation is correct the brackets don't give any additional information. – Voo Nov 05 '11 at 16:18
  • I just ran into this in answering another question; the code had a for (...) try { ... } catch { ... }. No curly-braces around the try/catch, and the end was about 10 lines after the start. Did finally spot it. :) – cahuson Jan 17 '14 at 18:58
  • @verdan Another reason to use braces is that if you post poorly formatted code on Stack Overflow, sometimes a guy who has edited hundreds of posts to improve formatting will [flatly refuse to help you](http://stackoverflow.com/q/21947066/1248365) if you omit braces and will link to this answer instead. ;) BTW, Jon Skeet is considered a 4-star general around here, not a sergeant. – Adi Inbar Feb 22 '14 at 05:23
  • 4
    More argument to use ALWAYS the braces: https://www.imperialviolet.org/2014/02/22/applebug.html – MrTJ Mar 05 '14 at 15:00
  • 2
    Or... don't let a python dev work on java code ;-) – Déjà vu Dec 03 '15 at 08:31
  • There's this wave of Python influence where Java developers look for lazy shortcuts - omitting squiggly brackets and the likes and end up spending hours debugging stuffs like this that should have been written properly from start. In Python world indentation is their biggest saviour. – theyCallMeJun Apr 11 '16 at 04:31
  • can not using brackets cause a program to fail –  May 06 '17 at 04:04
  • 1
    @theProgrammer101: Yes, if you then add another statement and don't spot that you don't have the braces, as per my first snippet... – Jon Skeet May 06 '17 at 05:57
37

Using braces makes the code more maintainable and understandable. So you should consider them by default.

I sometimes skip using braces on guard clauses to make the code more compact. My requirement for this is that they're if statements that are followed by a jump statement, like return or throw. Also, I keep them in the same line to draw attention to the idiom, e.g:.

if (!isActive()) return;

They also apply to code inside loops:

for (...) {
  if (shouldSkip()) continue;
  ...
}

And to other jump-conditions from methods that are not necessarily at the top of the method body.

Some languages (like Perl or Ruby) have a kind of conditional statement, where braces don't apply:

return if (!isActive());
// or, more interestingly
return unless (isActive());

I consider it to be equivalent to what I just described, but explicitly supported by the language.

Jordão
  • 55,340
  • 13
  • 112
  • 144
  • 7
    +1 guard clauses inside loops are usually more clear without the curly braces. – Viccari Jul 04 '12 at 18:48
  • 2
    Agreed on the guard clauses. Makes the code more readable in my opinion and actually increases maintainability. The points that the accepted answer makes are very valid though, so I'd limit the omission of braces to guard clauses. – ChrisK Jan 16 '15 at 12:44
12

There is no difference. The main problem with the second version is you might end up writing this:

for (...) 
  do_something();
  do_something_else();

when you update that method, thinking that do_something_else() is called inside the loop. (And that leads to head-scratching debug sessions.)

There is a second problem that the brace version doesn't have, and its possibly even harder to spot:

for (int i=0; i<3; i++);
  System.out.println("Why on earth does this print just once?");

So keep the braces unless you have a good reason, it is just a few keystrokes more.

Mat
  • 202,337
  • 40
  • 393
  • 406
  • 3
    The first point is good, but the second point is wrong. The brace version can still have that problem. for (int i=0;i<3;i++); { System.out.println("Why does this print just once?"); }. I know because I always use braces, but sometimes erroneously add extra semicolons. – emory Nov 05 '11 at 15:49
  • 3
    The brace version can have it, but it is more visible if the brace is on the same line. With the brace on the next line, indeed, it's pretty much as nasty. – Mat Nov 05 '11 at 15:51
  • The second version for me is as important as the first, because looking at the second version it is almost impossible to spot what is wrong until you actually run it to see what in the world is going on. Developers spend a lot of time debugging code like this which would easily be spotted had those squiggly bracket been introduced. For me, omitting those squiggly brackets is not just a matter of style but a good indicator of probable buggy code. – theyCallMeJun Apr 11 '16 at 04:22
7

For most cases, the answers mentioned so far are correct. But there are some disadvantages to it from the security perspective of things. Having worked in a payments team, security is a much stronger factor that motives such decisions. Lets say you have the following code:

if( "Prod".equals(stage) )
  callBankFunction ( creditCardInput )
else
  callMockBankFunction ( creditCardInput )

Now lets say you have this code is not working due to some internal problem. You want to check the input. So you make the following change:

if( "Prod".equals(stage) )
  callBankFunction ( creditCardInput )
else
  callMockBankFunction ( creditCardInput )
  Logger.log( creditCardInput )

Say you fix the problem and deploy this code (and maybe the reviewer & you think this won't cause a problem since its not inside the 'Prod' condition). Magically, your production logs now print customer credit card information that is visible to all the personnel who can see the logs. God forbid if any of them (with malicious intent) gets hold of this data.

Thus not giving a brace and a little careless coding can often lead to breach of secure information. It is also classified as a vulnerability in JAVA by CERT - Software Engineering Institure, CMU.

kung_fu_coder
  • 146
  • 2
  • 3
  • I'd argue that's a pretty terrible design in the first place, but the point is valid. – Christopher Schneider Nov 22 '16 at 14:30
  • Really good point. I would argue if you are working with such sensitive data then a lot of the things we do for programmer happiness take a backseat to verbose, less error prone code. But, for the vast majority of us (I would say), not using brackets in single line `if`/`else` statements are much nicer to parse and follow. – Joshua Pinter Jul 13 '23 at 13:22
6

I think that loosing curly braces is good, if you are also using auto-format, because than your indentation is always correct, so it will be easy to spot any errors that way.

Saying that leaving the curly braces out is bad, weird or unreadable is just wrong, as whole language is based on that idea, and it's pretty popular (python).

But I have to say that without using a formatter it can be dangerous.

Máté Magyar
  • 113
  • 2
  • 7
4

If you have a single statement you can omit the brackets, for more that one statements brackets is necessary for declaring a block of code.

When you use brackets you are declaring a block of code :

{

//Block of code
}

The brackets should be used also with only one statement when you are in a situation of nested statement for improve readability, so for example :

for( ; ; )
  if(a == b) 
    doSomething()

it is more readable written with brackets also if not necessary :

for( ; ; ) {
  if(a == b) {
    doSomething()
   }
}
aleroot
  • 71,077
  • 30
  • 176
  • 213
  • Exactly :) More readable = less effort required. So in order to prevent possible future mistakes we all end up in a mud of brackets, we need to see and write :) – Zbyszek Nov 17 '21 at 09:35
4

If you use brackets your code is more readable. And if you need to add some operator in same block you can avoid possible errors

Sergey Gazaryan
  • 1,013
  • 1
  • 9
  • 25
  • No. Using brackets in case of single instruction makes code less readable cause you feed your eyes and mind with more symbols which - in that case - brings no additional info. And this is why phyton become popular. Programing in that language cost you less effort, cause it's code is shorter and have less unnesesary elems. – Zbyszek Nov 17 '21 at 09:33
3

using redundant braces to claim that code is more maintainable raises the following question: if the guys writing, wondering about and further maintaining the code have issues like the ones described before (indentation related or readability related) perhaps they should not program at all...

3

Nowadays, it is very easy to re-indent codes to find out which block of codes is in which if or for/while. If you insist that re-indenting is hard to do, then brackets placed at wrong indentation can confuse you equally badly.

for(int i = 0; i < 100; i++) { if(i < 10) {
    doSomething();
} else { for(int j = 0; j < 5; j++) {
        doSomethingElse();
    }
}}

If you do this everywhere, your brain is going to break down in no time. Even with brackets, you are depending on indentation to visually find the start and end of code blocks.

If indentation is important, then you should already write your code in correct indentation, so other people don't need to re-indent your codes to read correctly.

If you want to argue that the previous example is too fake/deliberate, and that the brackets are there to capture careless indentation problem (especially when you copy/paste codes), then consider this:

for(int i = 0; i < 100; i++) {
    if(i < 10) {
    doSomething();
}
else {
    for(int j = 0; j < 5; j++) {
        doSomethingElse();
    }
}

Yes, it looks less serious than the previous example, but you can still get confused by such indentation.

IMHO, it is the responsibility of the person writing the code to check through the code and make sure things are indented correctly before they proceed to do other things.

Jai
  • 8,165
  • 2
  • 21
  • 52
3

Using the brackets future proofs the code against later modifications. I've seen cases where brackets were omitted and someone later added some code and didn't put the brackets in at that time. The result was that the code they added didn't go inside the section they thought it did. So I think the answer is that its good practice in light of future changes to the code. I've seen software groups adopt that as a standard, i.e. always requiring brackets even with single line blocks for that reason.

Nerdtron
  • 1,486
  • 19
  • 32
  • I agree with this. The brackets aren't for you. They're for the person that comes behind you. Several times, I've had code I was maintaining that I was unfamiliar with that didn't use brackets and had bad indentation. At this stage, I'm probably fixing a bug, so it's good to know what's supposed to happen. Omitting braces makes it less obvious, and I have to step through the code, wasting time. – Christopher Schneider Nov 22 '16 at 14:38
  • One may protect against everything. That will be perfect. But not livable :) – Zbyszek Nov 17 '21 at 09:36
2

If you remove braces, it will only read the first line of instruction. Any additional lines will not be read. If you have more than 1 line of instruction to be executed pls use curly brace - or else exception will be thrown.

Ashish Patel
  • 163
  • 6
2

More support for the "always braces" group from me. If you omit braces for single-statement loops/branches, put the statement on the same line as the control-statement,

if (condition) doSomething();
for(int i = 0; i < arr.length; ++i) arr[i] += b;

that way it's harder to forget inserting braces when the body is expanded. Still, use curlies anyway.

Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431
1

Result wise , it is the same thing.

Only two things to consider.

- Code Maintainability
- Loosely coupled code. (may execute something else. because you haven't specified the scope for the loop. )

Note: In my observation, if it is loop with in a loop. Inner Loop without braces is also safe. Result will not vary.

Sireesh Yarlagadda
  • 12,978
  • 3
  • 74
  • 76
1

If you have only one statement inside the loop it is same.

For example see the following code:

for(int i=0;i<4;i++)
            System.out.println("shiva");

we have only one statement in above code. so no issue

for(int i=0;i<4;i++)
            System.out.println("shiva");
            System.out.println("End");

Here we are having two statements but only first statement comes into inside the loop but not the second statement.

If you have multiple statements under single loop you must use braces.

NShiva
  • 60
  • 10
0

it should be a reflex to reformat the code as well... that is of course for professional programmers in professional teams

0

It's probably best to use the curly braces everywhere for the simple fact that debugging this would be an extreme nuisance. But other wise, one line of code doesn't necessarily need the bracket. Hope this helps!

Ash_s94
  • 787
  • 6
  • 19