使用不带花括号的 if 语句是一种不好的做法吗?

发布于 2024-08-19 03:56:14 字数 1431 浏览 6 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(15

你丑哭了我 2024-08-26 03:56:14

第一个版本的问题在于,如果您返回并向 if 或 else 子句添加第二条语句,而没有记住添加大括号,则您的代码将以意想不到的且有趣的方式中断。

从可维护性角度来看,使用第二种形式总是更明智。

编辑:内德在评论中指出了这一点,但我认为也值得链接到这里。这不仅仅是一些象牙塔假设的废话:https://www.imperialviolet。 org/2014/02/22/applebug.html

The problem with the first version is that if you go back and add a second statement to the if or else clauses without remembering to add the curly braces, your code will break in unexpected and amusing ways.

Maintainability-wise, it's always smarter to use the second form.

EDIT: Ned points this out in the comments, but it's worth linking to here, too, I think. This is not just some ivory-tower hypothetical bullshit: https://www.imperialviolet.org/2014/02/22/applebug.html

傾城如夢未必闌珊 2024-08-26 03:56:14

省略语句块的一个问题是 else 歧义。也就是说,受 C 启发的语言忽略缩进,因此无法将其分开:

if(one)
    if(two)
        foo();
    else
        bar();

从此:

if(one)
    if(two)
        foo();
else
    bar();

One problem with leaving out statement blocks is the else-ambiguity. That is C-inspired languages ignore indentation and so have no way of separating this:

if(one)
    if(two)
        foo();
    else
        bar();

From this:

if(one)
    if(two)
        foo();
else
    bar();
暖树树初阳… 2024-08-26 03:56:14

我的一般模式是,如果它适合一行,我会这样做:

if(true) do_something();

如果有一个 else 子句,或者如果我想在 true 上执行的代码非常长,则一直用大括号:

if(true) {
    do_something_and_pass_arguments_to_it(argument1, argument2, argument3);
}

if(false) {
    do_something();
} else {
    do_something_else();
}

最终,它归结为风格和可读性的主观问题。然而,一般的编程世界几乎分为两派(对于使用大括号的语言):要么毫无例外地一直使用它们,要么毫无例外地一直使用它们。我属于后一组。

My general pattern is that if it fits on one line, I'll do:

if(true) do_something();

If there's an else clause, or if the code I want to execute on true is of significant length, braces all the way:

if(true) {
    do_something_and_pass_arguments_to_it(argument1, argument2, argument3);
}

if(false) {
    do_something();
} else {
    do_something_else();
}

Ultimately, it comes down to a subjective issue of style and readability. The general programming world, however, pretty much splits into two parties (for languages that use braces): either use them all the time without exception, or use them all the time with exception. I'm part of the latter group.

倾听心声的旋律 2024-08-26 03:56:14

我遵循的“规则”是这样的:

如果“if”语句正在测试以执行某些操作(IE 调用函数、配置变量等),请使用大括号。

if($test)
{
    doSomething();
}

这是因为我觉得你需要弄清楚正在调用哪些函数以及程序流将在什么情况下流向何处。让程序员准确地理解在这种情况下调用了哪些函数以及设置了哪些变量对于帮助他们准确地理解程序正在做什么非常重要。

如果“if”语句正在测试以停止执行某些操作(即循环或函数内的流控制),请使用单行。

if($test) continue;
if($test) break;
if($test) return;

在这种情况下,对程序员来说重要的是快速发现您不希望代码运行的异常情况,而这一切都包含在 $test 中,而不是在执行块中。

The "rule" I follow is this:

If the "if" statement is testing in order to do something (I.E. call functions, configure variables etc.), use braces.

if($test)
{
    doSomething();
}

This is because I feel you need to make it clear what functions are being called and where the flow of the program is going, under what conditions. Having the programmer understand exactly what functions are called and what variables are set in this condition is important to helping them understand exactly what your program is doing.

If the "if" statement is testing in order to stop doing something (I.E. flow control within a loop or function), use a single line.

if($test) continue;
if($test) break;
if($test) return;

In this case, what's important to the programmer is discovering quickly what the exceptional cases are where you don't want the code to run, and that is all coverred in $test, not in the execution block.

话少情深 2024-08-26 03:56:14

我正在使用我所使用的 IDE 的代码格式化程序。这可能有所不同,但可以在首选项/选项中进行设置。

我喜欢这个:

if (statement)
{
    // comment to denote in words the case
    do this;
    // keep this block simple, if more than 10-15 lines needed, I add a function for it
}
else
{
    do this;
}

I am using the code formatter of the IDE I use. That might differ, but it can be setup in the Preferences/Options.

I like this one:

if (statement)
{
    // comment to denote in words the case
    do this;
    // keep this block simple, if more than 10-15 lines needed, I add a function for it
}
else
{
    do this;
}
写给空气的情书 2024-08-26 03:56:14

从一开始就使用大括号应该有助于防止您必须进行调试:

if (statement)
     do this;
else
     do this;
     do that;

Having the braces right from the first moment should help to prevent you from ever having to debug this:

if (statement)
     do this;
else
     do this;
     do that;
血之狂魔 2024-08-26 03:56:14

所有 if 语句(即使是简单的语句)都使用大括号。或者,重写一个简单的 if 语句以使用三元运算符:

if (someFlag) {
 someVar= 'someVal1';
} else {
 someVar= 'someVal2';
}

看起来更好,如下所示:

someVar= someFlag ? 'someVal1' : 'someVal2';

但仅当您绝对确定 if/else 块中没有其他内容需要时才使用三元运算符!

Use braces for all if statements even the simple ones. Or, rewrite a simple if statement to use the ternary operator:

if (someFlag) {
 someVar= 'someVal1';
} else {
 someVar= 'someVal2';
}

Looks much nicer like this:

someVar= someFlag ? 'someVal1' : 'someVal2';

But only use the ternary operator if you are absolutely sure there's nothing else that needs to go in the if/else blocks!

忱杏 2024-08-26 03:56:14

我更喜欢使用牙套。添加大括号可以更轻松地阅读和修改。

以下是一些使用大括号的链接:

I prefer using braces. Adding braces makes it easier to read and modify.

Here are some links for the use of braces:

简单气质女生网名 2024-08-26 03:56:14

根据我的经验,第一种形式唯一(非常)轻微的优势是代码可读性,第二种形式增加了“噪音”。

但对于现代 IDE 和代码自动生成(或自动完成),我强烈建议使用第二种形式,您不会花费额外的时间键入大括号,并且可以避免一些最常见的错误。

消耗能量的虫子已经够多了,人们不应该为了浪费时间而打开大门。

编写代码时要记住的最重要的规则之一是一致性。每一行代码都应该以相同的方式编写,无论是谁编写的。严谨可以防止错误“发生”;)

这与明确命名和命名相同。明确你的变量、方法、文件或正确缩进它们......

当我的学生接受这个事实时,他们不再与自己的源代码作斗争,他们开始将编码视为一项非常有趣、刺激和创造性的活动。他们挑战的是他们的思想,而不是他们的神经!

From my experience the only (very) slight advantage of the first form is code readability, the second form adds "noise".

But with modern IDEs and code autogeneration (or autocompletion) I strongly recommend using the second form, you won't spend extra time typing curly braces and you'll avoid some of the most frequent bugs.

There are enough energy consuming bugs, people just shoudn't open doors for big wastes of time.

One of the most important rule to remember when writing code is consistency. Every line of code should be written the same way, no matter who wrote it. Being rigorous prevents bugs from "happening" ;)

This is the same with naming clearly & explicitly your variables, methods, files or with correctly indenting them...

When my students accept this fact, they stop fighting against their own sourcecode and they start to see coding as a really interesting, stimulating and creative activity. They challenge their minds, not their nerves !

烂柯人 2024-08-26 03:56:14

就我个人而言,我使用第一种样式仅抛出异常或过早地从方法返回。就像在函数开头进行参数检查一样,因为在这些情况下,我很少有不止一件事要做,而且从来没有其他事情。

示例:

if (argument == null)
    throw new ArgumentNullException("argument");

if (argument < 0)
    return false;

否则我使用第二种样式。

Personally I use the first style only throw an exception or return from a method prematurely. Like argument Checking at the beginning of a function, because in these cases, rarely do I have have more than one thing to do, and there is never an else.

Example:

if (argument == null)
    throw new ArgumentNullException("argument");

if (argument < 0)
    return false;

Otherwise I use the second style.

著墨染雨君画夕 2024-08-26 03:56:14

这是一个偏好问题。我个人使用这两种样式,如果我有理由确定不需要添加更多语句,我会使用第一种样式,但如果可能的话,我会使用第二种样式。由于您无法向第一种样式添加更多语句,因此我听说有些人建议不要使用它。但是,第二种方法确实会产生额外的代码行,并且如果您(或您的项目)使用这种编码风格,则对于简单的 if 语句来说,第一种方法是非常首选的:

if(statement)
{
    do this;
}
else
{
    do this;
}

但是,我认为解决此问题的最佳方法是在Python中。使用基于空格的块结构,您没有两种不同的方法来创建 if 语句:您只有一种:

if statement:
    do this
else:
    do this

虽然这确实存在根本无法使用大括号的“问题”,但您确实获得了好处是它不再需要第一种样式的行,并且能够添加更多语句。

It is a matter of preference. I personally use both styles, if I am reasonably sure that I won't need to add anymore statements, I use the first style, but if that is possible, I use the second. Since you cannot add anymore statements to the first style, I have heard some people recommend against using it. However, the second method does incur an additional line of code and if you (or your project) uses this kind of coding style, the first method is very much preferred for simple if statements:

if(statement)
{
    do this;
}
else
{
    do this;
}

However, I think the best solution to this problem is in Python. With the whitespace-based block structure, you don't have two different methods of creating an if statement: you only have one:

if statement:
    do this
else:
    do this

While that does have the "issue" that you can't use the braces at all, you do gain the benefit that it is no more lines that the first style and it has the power to add more statements.

貪欢 2024-08-26 03:56:14

我一直试图使我的代码标准化并看起来尽可能接近相同。这使得其他人在负责更新时更容易阅读它。如果您执行第一个示例并在中间添加一行,它将失败。

不起作用:

if(语句)
这样做;
还有这个;
别的
这样做;

I have always tried to make my code standard and look as close to the same as possible. This makes it easier for others to read it when they are in charge of updating it. If you do your first example and add a line to it in the middle it will fail.

Won't work:

if(statement)
do this;
and this;
else
do this;

任谁 2024-08-26 03:56:14

我个人的偏好是使用空格和括号的混合,如下所示:

if( statement ) {

    // let's do this

} else {

    // well that sucks

}

我认为这看起来很干净,并使我的代码非常易于阅读,最重要的是 - 调试。

My personal preference is using a mixture of whitespace and brackets like this:

if( statement ) {

    // let's do this

} else {

    // well that sucks

}

I think this looks clean and makes my code very easy to read and most importantly - debug.

爱你不解释 2024-08-26 03:56:14

我同意大多数答案,因为最好在代码中明确并使用大括号。就我个人而言,我会采用一套编码标准,并确保团队中的每个人都了解并遵守它们。在我工作的地方,我们使用 IDesign.net 为 .NET 项目发布的编码标准。

I agree with most answers in the fact that it is better to be explicit in your code and use braces. Personally I would adopt a set of coding standards and ensure that everyone on the team knows them and conforms. Where I work we use coding standards published by IDesign.net for .NET projects.

万劫不复 2024-08-26 03:56:14

我更喜欢放一个大括号。但有时,三元运算符会有所帮助。

而不是:

int x = 0;
if (condition) {
    x = 30;
} else {
    x = 10;
}

人们应该简单地这样做: int x = condition ? 30 : 20;

再想象一个情况:

if (condition)
    x = 30;
else if (condition1)
    x = 10;
else if (condition2)
    x = 20;

如果把大括号放进去会好很多。

I prefer putting a curly brace. But sometimes, ternary operator helps.

In stead of :

int x = 0;
if (condition) {
    x = 30;
} else {
    x = 10;
}

One should simply do : int x = condition ? 30 : 20;

Also imagine a case :

if (condition)
    x = 30;
else if (condition1)
    x = 10;
else if (condition2)
    x = 20;

It would be much better if you put the curly brace in.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文