在 Java 中省略大括号可以吗?

我一直在找这个,但是找不到答案不管是什么原因,我都不好意思去问教授,因为当成百上千的人盯着你看的时候,那种感觉..。

无论如何,我的问题是有括号的重要性是什么? 如果我省略它们可以吗? 例如:

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

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

我知道这两个方法都可行,但是如果我省略了方括号(由于可见性,我倾向于做很多工作) ,这会改变任何事情吗?就像我说的,我知道它能用,我测试了很多次,但是现在我的一些大学作业变得越来越大了,出于某种原因,我非理性地担心,从长远来看,这会导致一些问题?有什么好担心的吗?

75245 次浏览

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.

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

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.

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

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

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.

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.

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.

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.

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.

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.

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.

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

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

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!

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.