如果我在 Java 中省略花括号可以吗? [英] Is it ok if I omit curly braces in Java?

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

问题描述

我已经搜索过这个,但找不到答案,无论出于何种原因,我都不好意思问教授,因为当数百人盯着你时的感觉......

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;
}

对比

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?

推荐答案

它不会改变任何除了代码的可维护性.我见过这样的代码:

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

...但是应该是这样的:

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

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

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