Is it ok if I omit curly braces in Java?

JavaCoding StyleBrackets

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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).

Solution 2 - Java

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.

Solution 3 - Java

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.

Solution 4 - Java

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.

Solution 5 - Java

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.

Solution 6 - Java

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()
   }
}

Solution 7 - Java

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

Solution 8 - Java

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.

Solution 9 - Java

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...

Solution 10 - Java

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.

Solution 11 - Java

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.

Solution 12 - Java

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.

Solution 13 - Java

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.

Solution 14 - Java

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.

Solution 15 - Java

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

Solution 16 - Java

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!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionvedranView Question on Stackoverflow
Solution 1 - JavaJon SkeetView Answer on Stackoverflow
Solution 2 - JavaJordãoView Answer on Stackoverflow
Solution 3 - JavaMatView Answer on Stackoverflow
Solution 4 - JavaMáté MagyarView Answer on Stackoverflow
Solution 5 - Javakung_fu_coderView Answer on Stackoverflow
Solution 6 - JavaalerootView Answer on Stackoverflow
Solution 7 - JavaSergey GazaryanView Answer on Stackoverflow
Solution 8 - JavaNerdtronView Answer on Stackoverflow
Solution 9 - Javauser962247View Answer on Stackoverflow
Solution 10 - JavaDaniel FischerView Answer on Stackoverflow
Solution 11 - JavaJaiView Answer on Stackoverflow
Solution 12 - JavaSireesh YarlagaddaView Answer on Stackoverflow
Solution 13 - JavaNShivaView Answer on Stackoverflow
Solution 14 - JavaAshish PatelView Answer on Stackoverflow
Solution 15 - Javauser962247View Answer on Stackoverflow
Solution 16 - JavaAsh_s94View Answer on Stackoverflow