Is it ok if I omit curly braces in Java?

I was looking for this, but could not find the answer, and for some reason I was too ashamed to ask the professor because of this feeling when hundreds of people look at you ...

Anyway, my question is the importance of having parentheses? Is it okay if I omit them? Example:

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

against

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

I know that both of them will work, but if I omit the brackets (which I usually do a lot, because of visibility), will this change anything, anything at all? Like I said, I know that it works, I tested it a dozen times, but now some of my uni assignments are getting bigger and for some reason I have an irrational fear that this will eventually cause some problems? Is there any reason to be afraid of this?

+60
java coding-style brackets
Nov 05 2018-11-11T00:
source share
17 answers

This will not change anything other than the maintainability of your code. I saw a code like this:

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

which means the following:

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

... but it should have been like this:

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

Personally, I always include brackets to reduce the chance of confusion when reading or changing code.

The coding agreements in each company I worked for required this - this does not mean that some other companies do not have different agreements ...

And just in case, if you think that this will never change the situation: I had to fix a mistake that was pretty much equivalent to the code above. It was very difficult to notice ... (admittedly, this was many years ago before I started unit testing, which would undoubtedly facilitate the diagnosis).

+96
Nov 05 2018-11-11T00:
source share

Using curly braces makes the code more convenient and understandable. Therefore, you should consider them by default.

I sometimes skip braces on watchdog sentences to make the code more compact. My requirement for this is that they are if followed by a jump statement, such as return or throw . In addition, I keep them on the same line to draw attention to the idiom, for example :.

 if (!isActive()) return; 

They also apply to internal code loops:

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

And for other transition conditions from methods that are not necessarily located in the upper part of the method body.

Some languages ​​(for example, Perl or Ruby) have a kind of conditional expression, where curly braces are not used:

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

I believe this is equivalent to what I just described, but clearly supported by the language.

+26
Nov 05 2018-11-15T00:
source share

There is no difference. The main problem with the second version is that you can write this:

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

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

There is a second problem that is missing from the version of the bracket, and it may be even more difficult to determine:

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

So keep braces, unless you have a good reason, these are just a few keystrokes.

+10
Nov 05 '11 at 12:44
source share

I do not see the point of the agreement.

The reason to always use curly braces is rather weak, because it was assumed that the programmer knows the syntax of the language and knows that the if-statement without bindings applies only to the first expression following it.

if Oracle decides that “good practice” always writes an if-statement with curly braces, then why don't they just change the syntax?

My opinion:

If I write "without curly braces operator", I always put it on one line. Put in two lines this type of code is strange:

 if(statement) code; // weird and ugly for me. if(statement) code; // ok for me, I often use in very short codes. // but if the code is long, so I prefer the code below. if(statement) { code; // if this makes your code clear, then ok. // But there is cases when I think the second option is better. } 

I don't like agreements based on such stupid reasons.

Added: many people in this post agreed on the same thing: you have to do this in order to improve readability. But I think that doing this in order to avoid mistakes is not necessary.

Do you think you should change this code:

 while(statement) { if (condition) i++; } 

in it:

 while(statement) { if (condition) { i++; } } 

improve readability? I do not think so. This may be a more complicated if-statement. But everyone I know code this way only in simple if statements. True, the first case looks clearer.

But someone thinks that there is an opportunity for a programmer to do this:

 while (statement) { if (condition) i++; statement; } 

thinking that this statement will be part of if. I think there is no need to worry about this. Because if some programmer is capable of this, it would be worse.

I think that should be avoided - write without braces if-statement in two lines:

 while (statement) { if (condition) i++; statement; } 

or a nest decouples expressions like:

 while (statement) if (condition) i++; 

I agree with his penchant for mistakes, and this is often done by beginners. You should avoid writing complex if similar statements without curly braces.

+5
Jul 26 '13 at 5:06 on
source share

If you have one statement, you can omit the parentheses, because declaring a code block requires more than one statement bracket.

When you use parentheses, you declare a block of code:

 { //Block of code } 

Brackets should also be used with only one statement when you are in a nested statement situation to improve readability, for example:

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

it is more readable, writing with brackets, if it is not necessary:

 for( ; ; ) { if(a == b) { doSomething() } } 
+4
Nov 05 '11 at 12:45
source share

If you use parentheses, your code is more readable. And if you need to add any operator in the same block, you can avoid possible errors.

+4
Nov 05 2018-11-11T00:
source share

I think losing curly braces is good if you also use auto-format, because your indentation is always correct, so it will be easy to detect any errors in this way.

Saying that leaving curly braces bad, strange or unreadable is simply wrong, as the whole language is based on this idea, and it is pretty popular (python).

But I have to say that without using formatting this can be dangerous.

+4
May 6 '14 at 9:00
source share

The use of parentheses in the future confirms the code with later changes. I saw cases where the brackets were omitted, and someone later added some code and did not insert the brackets at this time. As a result, the code they added did not get into the section that they thought he made. So I think the answer is that its a good practice in light of future changes to the code. I have seen software groups take this as a standard, i.e. Always require brackets even with single line blocks for this reason.

+3
Nov 05 '11 at 12:45
source share

In most cases, the answers mentioned so far are correct. But there are some drawbacks in terms of the safety of things. Work in a payment team, security is a much stronger factor that motivates such decisions. Let's say you have the following code:

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

Now let's say that this code does not work due to some internal problem. You want to check the input. Therefore, you make the following change:

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

Suppose you fix a problem and deploy this code (and possibly a reviewer, and you think this will not cause a problem, because it is not in the "Prod" state). Magically, your production logs now print out customer credit card information that is visible to all employees who can see the logs. God forbid, if any of them (with malicious intent) take possession of this data.

Thus, the lack of binding and a little careless coding can often lead to a breach of protected information. It is also classified as a vulnerability in the JAVA CERT - Software Engineering Institure, CMU .

+3
Dec 03 '15 at 8:13
source share

More support from the always-ups group from me. If you omit curly braces for loops / branches of the same statement, 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; 

so it’s harder to forget to insert braces when the body expands. However, use curls.

+2
Nov 05 2018-11-11T00:
source share

The result is wise, it is the same.

There are only two things to consider.

- Maintaining code health
- Loosely linked code. (something else may be executed. because you did not specify the scope of the loop.)

Note. In my observation, if this is a loop with a loop. The brace-free inner loop is also safe. The result will not change.

+1
Jul 31 '15 at 3:48
source share

If you remove the curly braces, it will read only the first line of the instruction. Any additional lines will not be read. If you have more than one line of instructions for executing PLS, use curly braces - otherwise an exception will be thrown.

+1
Jan 06 '17 at 4:30
source share

If you have only one statement inside the loop, it will be the same.

For example, see the following code:

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

there is only one statement in the above code. so no problem

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

Here we have two operators, but only the first operator enters the loop, but not the second operator.

If you have multiple statements in the same loop, you should use curly braces.

0
Nov 04 '15 at 7:28
source share

using red curly brackets to claim that the code is more convenient to maintain, the following question arises: if the guys write, are interested and continue to maintain the code, there are problems similar to those described earlier (indentation or reading related), maybe they should not program for everything ...

0
Feb 27 '17 at 5:58
source share

it should be a reflex for reformatting the code ... this, of course, for professional programmers in professional teams

0
Feb 27 '17 at 6:00
source share

It is probably best to use braces everywhere for the simple fact that debugging this will be extremely unpleasant. But, in addition, one line of code is not necessary for the parenthesis. Hope this helps!

0
Oct 29 '17 at 19:46 on
source share

It is now very easy to redraw codes to find out which block of codes is in if or for / while . If you insist that re-padding is difficult to complete, parentheses placed in the wrong indentation may confuse you equally.

 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 will break down in no time. Even with parentheses, you are indented to visually find the beginning and end of blocks of code.

If the indentation is important, then you should already write your code in the correct indentation, so other people do not need to re-specify the codes for proper reading.

If you want to claim that the previous example is too fake / intentional, and that there is a problem with indentation in brackets (especially when copying / pasting codes), 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 be confused by this indentation.

IMHO, the person who writes the code checks the code and verifies that the indentation is correct before they start doing other things.

0
Nov 22 '17 at 8:28
source share



All Articles