如果我在Java省略大括号是确定吗? [英] Is it ok if I omit curly braces in Java?

查看:166
本文介绍了如果我在Java省略大括号是确定吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我搜索过这个,但找不到答案,无论什么原因,我很ash愧地问教授,因为这种感觉,当几百人盯着你...

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;

我知道他们都会工作,但如果我省略括号很多,由于可见性)会改变任何东西,任何东西?正如我所说,我知道它的工作,我测试了它几十次,但现在一些我的uni任务正在变大,并且由于某种原因,我有不合理的恐惧,从长远来看,这我的原因一些问题?有理由担心吗?

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?

推荐答案

除了您的代码的可维护性。我看过这样的代码:

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");

这意味着:

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

并且为了防止你认为它永远不会有所作为:我不得不修复一个bug,这几乎相当于代码。这是非常难以发现...(无可否认,这是多年前,在我开始单元测试,这无疑会使诊断更容易)。

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

这篇关于如果我在Java省略大括号是确定吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆