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.
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:
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.
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.
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...
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.
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:
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.
if (condition) doSomething();
for(int i = 0; i < arr.length; ++i) arr[i] += b;
这样在主体展开时就很难忘记插入大括号。尽管如此,还是使用卷发吧。
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.
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.
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!
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 语句,后跟 jump 语句,例如 return 或 throw。另外,我将它们放在同一行以引起对成语的注意,例如:。
if (!isActive()) return;
它们还适用于循环内的代码:
for (...) {
if (shouldSkip()) continue;
...
}
以及不一定位于方法体顶部的方法中的其他跳转条件。
某些语言(如 Perl 或 Ruby)有一种条件语句,其中大括号不适用:
return if (!isActive());
// or, more interestingly
return unless (isActive());
我认为它等价于我刚刚描述的内容,但明确语言支持。
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.
发布评论
评论(16)
我认为,如果您还使用自动格式,那么松开大括号是件好事,因为您的缩进总是正确的,因此可以很容易地发现任何错误。
说去掉大括号不好、奇怪或不可读是错误的,因为整个语言都是基于这个想法的,而且它非常流行(python)。
但我不得不说,如果不使用格式化程序,它可能会很危险。
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.
对于大多数情况,到目前为止提到的答案都是正确的。但从安全角度来看,它也存在一些缺点。由于在支付团队工作过,安全性是促使此类决策的一个更重要的因素。假设您有以下代码:
现在假设您的代码由于某些内部问题而无法工作。您想检查输入。因此,您进行以下更改:
假设您修复了问题并部署了此代码(也许审阅者和您认为这不会导致问题,因为它不在“Prod”条件内)。神奇的是,您的生产日志现在可以打印客户信用卡信息,所有可以查看日志的人员都可以看到这些信息。上帝保佑他们中的任何一个(怀着恶意)获得这些数据。
因此,不加括号和稍不小心的编码通常会导致安全信息的泄露。它也被 CERT - 卡内基梅隆大学软件工程学院。
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:
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:
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 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 :
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 :
it is more readable written with brackets also if not necessary :
如果您使用括号,您的代码将更具可读性。
如果您需要在同一块中添加一些运算符,您可以避免可能的错误
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
使用括号可以保证代码不会被以后修改。我见过省略括号的情况,后来有人添加了一些代码,但当时没有放入括号。结果是他们添加的代码没有进入他们认为应该进入的部分。所以我认为答案是,鉴于未来代码的变化,这是一个很好的实践。我见过软件团队采用它作为标准,即出于这个原因,即使是单行块也总是需要括号。
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.
使用冗余大括号来声称代码更易于维护会引发以下问题:如果编写、思考和进一步维护代码的人遇到像前面描述的问题(缩进相关或可读性相关),也许他们根本不应该编程。 。
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...
如今,重新缩进代码以找出哪个代码块位于哪个
if
或for
/while
中非常容易。如果您坚持认为重新缩进很难,那么放置在错误缩进处的括号同样会让您感到困惑。如果你到处这样做,你的大脑很快就会崩溃。即使使用括号,您也需要依靠缩进来直观地找到代码块的开头和结尾。
如果缩进很重要,那么您应该已经以正确的缩进编写代码,这样其他人就不需要重新缩进您的代码才能正确阅读。
如果你想争论前面的例子太假/故意,并且括号是为了捕捉粗心的缩进问题(特别是当你复制/粘贴代码时),那么请考虑这一点:
是的,它看起来没有前面的例子那么严重,但您仍然会对这种缩进感到困惑。
恕我直言,编写代码的人有责任检查代码并确保在继续执行其他操作之前正确缩进。
Nowadays, it is very easy to re-indent codes to find out which block of codes is in which
if
orfor
/while
. If you insist that re-indenting is hard to do, then brackets placed at wrong indentation can confuse you equally badly.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:
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.
我对“永远大括号”团体的更多支持。 如果您省略单语句循环/分支的大括号,请将语句与控制语句放在同一行,
这样在主体展开时就很难忘记插入大括号。尽管如此,还是使用卷发吧。
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,
that way it's harder to forget inserting braces when the body is expanded. Still, use curlies anyway.
就结果而言,这是同一件事。
只需考虑两件事。
- 代码可维护性
- 松散耦合的代码。 (可以执行
其他的东西。因为你还没有指定循环的范围。 )
注意:根据我的观察,如果是循环与循环。没有支架的内环也是安全的。结果不会改变。
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:
we have only one statement in above code. so no issue
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.
如果去掉大括号,它只会读取第一行指令。任何额外的行都不会被读取。如果要执行的指令多于 1 行,请使用大括号 - 否则将引发异常。
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.
重新格式化代码也应该是一种本能……这当然是对于专业团队中的专业程序员来说
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!
除了代码的可维护性之外,它根本不会改变任何东西。我见过这样的代码:
这意味着:
...但是应该是这样的:
就我个人而言,我总是包含括号以减少阅读时混淆的可能性或者修改代码。
我工作过的每家公司的编码约定都要求这样做 - 这并不是说其他一些公司没有不同的约定......
以防万一您认为它永远不会产生影响:我必须修复一次错误,几乎等同于上面的代码。这是非常难以发现的......(诚然,这是几年前的事,在我开始单元测试之前,这无疑会让诊断变得更容易)。
It won't change anything at all apart from the maintainability of your code. I've seen code like this:
which means this:
... but which should have been this:
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
语句,后跟 jump 语句,例如return
或throw
。另外,我将它们放在同一行以引起对成语的注意,例如:。它们还适用于循环内的代码:
以及不一定位于方法体顶部的方法中的其他跳转条件。
某些语言(如 Perl 或 Ruby)有一种条件语句,其中大括号不适用:
我认为它等价于我刚刚描述的内容,但明确语言支持。
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, likereturn
orthrow
. Also, I keep them in the same line to draw attention to the idiom, e.g:.They also apply to code inside loops:
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:
I consider it to be equivalent to what I just described, but explicitly supported by the language.
没有什么区别。第二个版本的主要问题是您最终可能会这样写:
当您更新该方法时,认为在循环内部调用了 do_something_else() 。 (这会导致令人头疼的调试会话。)
大括号版本没有第二个问题,而且可能更难发现:
所以保留大括号,除非你有充分的理由,这只是一些击键次数较多。
There is no difference. The main problem with the second version is you might end up writing this:
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:
So keep the braces unless you have a good reason, it is just a few keystrokes more.