Is it ok if I omit curly braces in Java? [closed]

2018-12-31 22:39发布

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?

16条回答
路过你的时光
2楼-- · 2018-12-31 23:20

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

查看更多
冷夜・残月
3楼-- · 2018-12-31 23:21

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.

查看更多
低头抚发
4楼-- · 2018-12-31 23:22

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.

查看更多
倾城一夜雪
5楼-- · 2018-12-31 23:29

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!

查看更多
登录 后发表回答