强制使用括号 [英] Mandatory use of braces

查看:160
本文介绍了强制使用括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为代码标准文档的一部分,我写了一段时间,我强制执行你必须始终使用大括号循环和/或条件代码块,甚至(特别是)如果它们只有一行。

As part of a code standards document I wrote awhile back, I enforce "you must always use braces for loops and/or conditional code blocks, even (especially) if they're only one line."

示例:

// this is wrong
if (foo) 
    //bar
else 
    //baz
while (stuff)
    //things

// This is right.
if (foo) {
    // bar
} else {
    // baz
}
while (things) {
    // stuff
}

当你不支持单行,它出来,你有麻烦。如果你不支持单行,缩进在其他人的机器上不显示相同...你有麻烦。

When you don't brace a single-line, and then someone comments it out, you're in trouble. If you don't brace a single-line, and the indentation doesn't display the same on someone else's machine... you're in trouble.

所以,问题:有什么好的理由为什么这会是一个错误或其他不合理的标准?

So, question: are there good reasons why this would be a mistaken or otherwise unreasonable standard? There's been some discussion on it, but no one can offer me a better counterargument than "it feels ugly".

推荐答案

我强制执行这到一个点,有一些例外,if语句评估为返回或继续循环。

I enforce this to a point, with minor exceptions for if statements which evaluate to either return or to continue a loop.

所以,这是正确的我的标准:

So, this is correct by my standard:

if(true) continue;

正如

if(true) return;

但规则是它是一个返回或继续,它都在同一行。

But the rule is that it is either a return or continue, and it is all on the same line. Otherwise, braces for everything.

推理是为了有一个标准的方法,并避免你提到的注释问题。

The reasoning is both for the sake of having a standard way of doing it, and to avoid the commenting problem you mentioned.

这篇关于强制使用括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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