简体   繁体   English

从java中的If语句中删除大括号有区别吗

[英]Is there a difference in removing the curly braces from If statements in java

While watching thenewbostons tutorial on basic java, he teaches us to do if statements like this.(Notice the curly Braces)在看newbostons关于java基础的教程时,他教我们做这样的if语句。(注意花括号)

if("pie"== "pie"){
    System.out.println("Hurrah!");
}

So I tried removing the curly braces所以我试着去掉花括号

if("pie"== "pie")
    System.out.println("Hurrah!");

And it still works!它仍然有效! Since I'm new to java, I don't know why that works.由于我是 Java 新手,我不知道为什么会这样。 And I want to know if removing(or adding) the curly braces give any benefits/disadvantages.我想知道删除(或添加)花括号是否有任何好处/坏处。

For a single statement it will remain same, but if you want to group more than one statement in the if block then you have to use curly braces.对于单个语句,它将保持不变,但如果要在 if 块中组合多个语句,则必须使用大括号。

if("pie"== "pie"){
    System.out.println("Hurrah!");
    System.out.println("Hurrah!2");
}

if("pie"== "pie")
    System.out.println("Hurrah!"); //without braces only this statement will fall under if
    System.out.println("Hurrah!2"); //not this one

You should see: Blocks in Java您应该会看到: Java 中的块

A block is a group of zero or more statements between balanced braces and can be used anywhere a single statement is allowed.块是平衡大括号之间的一组零个或多个语句,可以在允许单个语句的任何地方使用。 The following example, BlockDemo, illustrates the use of blocks:以下示例 BlockDemo 说明了块的使用:

class BlockDemo {
     public static void main(String[] args) {
          boolean condition = true;
          if (condition) { // begin block 1
               System.out.println("Condition is true.");
          } // end block one
          else { // begin block 2
               System.out.println("Condition is false.");
          } // end block 2
     }
}

(example from the above link) (上面链接中的例子)

No, there is absolutely no difference: a pair of curly braces makes multiple statements into a single one;不,绝对没有区别:一对花括号将多个语句合并为一个; if , while , for , and so on expect a single statement; ifwhilefor等期望一个语句; if you need to guard only one statement, you do not need braces.如果只需要保护一个语句,则不需要大括号。

However, many software shops insist on having braces even for a single statement.但是,许多软件商店甚至坚持要对单个语句使用大括号。 The reason is errors like this:原因是这样的错误:

if (x > 20)
    x -= 7;
    y -= 8;

The statements above are misleading: the indentation leads you to believe that both assignments are protected, while in reality only the first one is.上述陈述具有误导性:缩进使您相信两个赋值都受到保护,而实际上只有第一个是受保护的。 The reason for that is that whitespace in Java is insignificant: indenting a statement does not change its placement in the overall flow of the program.这样做的原因是 Java 中的空白是微不足道的:缩进语句不会改变它在整个程序流程中的位置。 Errors like the above are very hard to find, so adopting a rule to prevent them in the first place is a good idea.像上面这样的错误很难发现,因此首先采用规则来防止它们是一个好主意。

As @rajesh says, braces are optional when the body is a single statement.正如@rajesh 所说,当主体是单个语句时,大括号是可选的。

Having said that, leaving the braces in even for single statement cases is recommended by some coding styles because you (or the programmer who comes after you) are less likely to make errors when you change the code later.话虽如此,某些编码风格建议即使对于单语句情况也保留大括号,因为您(或跟随您的程序员)以后更改代码时出错的可能性较小。

if("pie"== "pie")
    System.out.println("Hurrah!");
    System.out.println("Tricked you");

The second print, Tricked you , is not actually in the if , it just looks like it because of the indentation.第二个打印, Tricked you ,实际上不在if ,它只是因为缩进而看起来像。

However that is only a style point, not universally accepted, and certainly a competent programmer needs to be able to read both forms.然而,这只是一个风格点,并没有被普遍接受,当然一个有能力的程序员需要能够阅读这两种形式。

This is a question of style that applies to a number of languages including Java, C++, C and C#.这是一个适用于多种语言的风格问题,包括 Java、C++、C 和 C#。

When a code block contains only one line the braces can be omitted.当代码块仅包含一行时,可以省略大括号。 This applies to any control structure: if, while, for, do-while.这适用于任何控制结构:if、while、for、do-while。

For example, the two loops below are equivalent.例如,下面的两个循环是等价的。

for(int i=0; i<100; i++)
  doSomething(i);



for(int i=0; i<100; i++) {
  doSomething(i);
}

Advantage of omitting {}: Your code can be briefer - meaning less line.省略 {} 的优势:您的代码可以更简短 - 意味着更少的行。 Some may feel it is more readable.有些人可能会觉得它更具可读性。

Disadvantage of omitting {}: If you later modify your code and need to add another line to the code block, you better remember to add those {}.省略 {} 的缺点:如果您稍后修改代码并需要在代码块中添加另一行,您最好记得添加那些 {}。 If not and you write the code below:如果没有,你写下面的代码:

for(int i=0; i<100; i++)
  doSomething(i);
  doSomethingElse(i);

This is really equivalent to:这实际上相当于:

for(int i=0; i<100; i++) {
  doSomething(i);
}
doSomethingElse(i);

It does have a disadvantage .它确实有一个缺点 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:假设您有以下代码:

if( "Prod".equals(stage) )
  callBankFunction ( creditCardInput )
else
  callMockBankFunction ( creditCardInput )

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:因此,您进行以下更改:

if( "Prod".equals(stage) )
  callBankFunction ( creditCardInput )
else
  callMockBankFunction ( creditCardInput )
  Logger.log( creditCardInput )

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).假设您解决了问题并部署了此代码(也许审阅者并且您认为这不会导致问题,因为它不在“Prod”条件内)。 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 .它也被CERT - 软件工程学院,CMU归类为 JAVA 中的一个漏洞。

If there is only one statement after if then braces are not mandatory.如果if之后只有一个语句,则大括号不是强制性的。

Now if you have a block of code which needs to fall under the if condition, then you need to use braces.现在,如果您有一段代码需要符合if条件,那么您需要使用大括号。

This holds good for loops as well这也适用于loops

The curly braces are usually for having a block of statements.花括号通常用于包含语句块。 Without braces, only the first line will be executed in the if() statement.如果没有大括号,则在if()语句中只会执行第一行。 Not the entire block that starts with { and ends with }不是以{开头并以}结尾的整个块

if("pie" == "pie") {
   System.out.println("Executes if pie==pie");
   System.out.println("So does this");
}

and

if("pie" == "pie")
   System.out.println("Executes if pie==pie");
System.out.println("Executes, regardless of if pie is equal to pie");

Note however, if you want to compare two String objects, use .equals() method in String .但是请注意,如果要比较两个String对象,请在String使用.equals()方法。 This example still works because it is comparing one constant string with itself, which is always true.这个例子仍然有效,因为它正在将一个常量字符串与其自身进行比较,这总是正确的。

No BUT the real danger occurs when the code is edited later on.不,但真正的危险发生在稍后编辑代码时。 It is relatively easy to edit something like:编辑以下内容相对容易:

if (someCondition) 
    // do something 

to

if (someCondition) 
    // do something
    // do something else important

and think the 'do something else important' will only be run when someCondition is true.并认为“做其他重要的事情”只会在 someCondition 为真时运行。 The indentation misleads :-)缩进会误导:-)

With brackets, this danger isn't present.有了括号,这种危险就不存在了。

It's the same, if the number of sentences is equal to one.如果句子数等于 1,则相同。 If there are more than one, you need the { } syntax如果有多个,则需要 {} 语法

My two cents.我的两分钱。 Writing two lines after an if statement without curly braces is a mistake I have never seen made.在没有花括号的 if 语句之后写两行是我从未见过的错误。 That said, the people you work with are bone heads who will not understand the magic trick you are pulling here.也就是说,与您一起工作的人都是笨蛋,他们不会理解您在这里使用的魔术。 Save fun things like this for your private code, but do what you are told in professional and classroom settings.为您的私人代码保存这样有趣的事情,但在专业和课堂环境中按照您的要求去做。

There is one actual argument on this that illustrates a reasonable issue that might arise.关于这一点,有一个实际论据说明了可能出现的一个合理问题。 As you may know, all indentation and extra whitespaces are removed from your code when it is being parsed.您可能知道,在解析代码时,所有缩进和多余的空格都会从代码中删除。 Troubles may arise when you try to use one-line else statements after multiple one-line if statements.当您尝试使用一个行可能出现的麻烦else后多一个行语句if语句。 For example:例如:

if("cherry".equals("cherry"))
    if("pie".equals("pie"))
        System.out.println("Hurrah!");
else
    System.out.println("Rats!");

becomes indistinguishable from变得无法区分

if("cherry".equals("cherry"))
    if("pie".equals("pie"))
        System.out.println("Hurrah!");
    else
        System.out.println("Rats!");

Even in that circumstance, an automatic tabbing set up should indicate which if statement the else is pointing to, but it is something you should certainly be wary of should you choose to skirt the rules as I often do.即使在这种情况下,自动制表符设置也应该表明else指向哪个if语句,但是如果您像我经常做的那样选择绕过规则,您当然应该警惕。

And I want to know if removing(or adding) the curly braces give any benefits/disadvantages?我想知道删除(或添加)花括号是否有任何好处/坏处?

The advantage with adding them always is that you can simply extend the code block later, without needing to add them.始终添加它们的优点是您可以稍后简单地扩展代码块,而无需添加它们。 Suppose you have:假设你有:

if("pie".equals("pie"))
    System.out.println("Hurrah!");

then, if you want to add an additional line of code, you need to make sure to add the braces:然后,如果要添加额外的代码行,则需要确保添加大括号:

if("pie".equals("pie")) {
    log.debug("I am here!");
    System.out.println("Hurrah!");
}

If they are already there, simply put the cursor to the end of the line, press return and start adding new code.如果它们已经存在,只需将光标放在行尾,按回车键并开始添加新代码。

For a single line, there is no difference technically, but many code conventions propose or even mandate to have them always there.对于单行,在技术上没有区别,但是许多代码约定建议甚至强制要求它们始终存在。 There is even aCheckStyle rule for it.甚至还有一个CheckStyle 规则

For a single statement not an issue对于单个语句不是问题

if("pie"== "pie")
System.out.println("Hurrah!");

For two or more statements after if you require the braces在 if 需要大括号之后的两个或多个语句

if("pie"== "pie"){
System.out.println("Hurrah!");
System.out.println("Hi!");
}

Also use .equals() for comparing rather than ==.也使用 .equals() 进行比较而不是 ==。

No, there is no difference between them with one statement in response to the if .不,它们之间没有区别,只有一个语句来响应if If you want to add a second statement in response to the if , then curly braces are required.如果要添加第二条语句以响应if ,则需要大括号。

It will work fine if there is only one statement after the if condition.如果在 if 条件之后只有一个语句,它将正常工作。

if("pie"== "pie")
    System.out.println("Hurrah!");
    System.out.println("second statement");// this will not print

but here both statement will print但这里两个语句都会打印

if("pie"== "pie")
{
System.out.println("Hurrah!");
System.out.println("second statement");
}

I would suggest you to use like below even if you want to print single statement.即使您想打印单个语句,我也建议您使用如下所示。

if("pie".equals("pie"))
   {
       System.out.println("Hurrah!");
       System.out.println("second statement");
   }

The curly braces is used only if you want to execute bunch of code in condition.仅当您想在条件下执行一堆代码时才使用花括号。 If you do not use the braces then it will only execute first statement after if condition.如果你不使用大括号,那么它只会在 if 条件之后执行第一条语句。 The remaining lines (below the first statement) will not consider as a if part.其余行(在第一个语句下方)不会被视为 if 部分。

If you add curly braces to this if statement:如果在此 if 语句中添加花括号:

if(++colorIndex == someColors.length)
            colorIndex = 0;
        setForeground(currentColor());
        repaint();

Then it wont work anymore.然后就不能用了。

So i think in some cases it does matter.所以我认为在某些情况下它确实很重要。

If there's a single statement inside an if-then, the {} curly braces can be omitted.如果 if-then 中只有一个语句,则可以省略 {} 大括号。 However, I tend to always include them as best coding practice since forgetting to use them with multiple statements inside an if-then will trigger an error.但是,我倾向于始终将它们包含为最佳编码实践,因为忘记将它们与 if-then 中的多个语句一起使用会触发错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM