所有其他答案都支持你的讲师规则3。
让我说,我同意你:规则是多余的,我不建议使用。确实,从理论上讲,如果您始终添加花括号,它可以防止错误。另一方面,与其他答案暗示的相反,我在现实生活中从未遇到过这个问题:一旦需要添加花括号,我从未忘记添加花括号。如果使用适当的缩进,一旦有多个语句缩进,需要再次添加花括号就变得显而易见了。
组件10的答案实际上强调了唯一可能导致错误的情况。但另一方面,通过正则表达式替换代码总是需要极大的小心。
现在让我们看看奖牌的另一面:总是使用花括号有什么
缺点吗?其他答案简单地忽略了这一点。但是确实存在一个缺点:它占用了很多垂直屏幕空间,这反过来可能会使您的代码难以阅读,因为这意味着您必须比必要的更多地滚动。
考虑一个函数,在开头有很多警卫条款(是的,在其他语言中,以下代码是糟糕的C++代码,但这种情况相当普遍):
void some_method(obj* a, obj* b)
{
if (a == nullptr)
{
throw null_ptr_error("a");
}
if (b == nullptr)
{
throw null_ptr_error("b");
}
if (a == b)
{
throw logic_error("Cannot do method on identical objects");
}
if (not a->precondition_met())
{
throw logic_error("Precondition for a not met");
}
a->do_something_with(b);
}
这是糟糕的代码,我强烈认为以下代码更易读:
void some_method(obj* a, obj* b)
{
if (a == nullptr)
throw null_ptr_error("a");
if (b == nullptr)
throw null_ptr_error("b");
if (a == b)
throw logic_error("Cannot do method on identical objects");
if (not a->precondition_met())
throw logic_error("Precondition for a not met");
a->do_something_with(b);
}
同样地,简短的嵌套循环受益于省略花括号:
matrix operator +(matrix const& a, matrix const& b) {
matrix c(a.w(), a.h());
for (auto i = 0; i < a.w(); ++i)
for (auto j = 0; j < a.h(); ++j)
c(i, j) = a(i, j) + b(i, j);
return c;
}
与之比较:
matrix operator +(matrix const& a, matrix const& b) {
matrix c(a.w(), a.h());
for (auto i = 0; i < a.w(); ++i)
{
for (auto j = 0; j < a.h(); ++j)
{
c(i, j) = a(i, j) + b(i, j);
}
}
return c;
}
第一段代码简洁;第二段代码臃肿。
是的,可以通过将左括号放在上一行来在某种程度上减轻这种情况。因此:如果您坚持使用花括号,请至少将左括号放在上一行。
简而言之:不要编写占用屏幕空间的不必要的代码。
自从我最初写下这个答案以来,我大多数时间都接受了普遍的代码风格,并使用花括号,除非我可以将整个单语句放在前一行。我仍然认为不使用冗余的花括号通常更易读,并且我仍然从未遇到由此引起的错误。
for (unsigned i = 100; i >= 0; --i)
。 - Archie(i % 2 == 0)
与(2)相矛盾。你在依赖运算符优先级,当然意思应该是((i % 2) == 0)
而不是(i % (2 == 0))
。我会将规则2分类为“有效的观点,但‘总是’是错误的”。 - Steve Jessop