Why should i give a name to an If Statement?

非 Y 不嫁゛ 提交于 2019-12-21 05:09:17

问题


I just discovered that i can give a name to For and While statements. I understand that it is useful if you want to break or continue a specific loop.
But why should i give a name to an If?? It looks useless

name: if(true){
    //do something
}

This compiles without problems


回答1:


If you have a code block with a name, you can use break to exit it, that is the use I have found for naming blocks.

name: if(true) {
    // do something
    if(/* condition */) {
        break name;
    }
    // do more
}

it also works without the if:

name: {
    // do something
    if(/* condition */) {
        break name;
    }
    // do more
}

This comes up in my work when there are a set of guard conditions on some logic, and another set of logic that will be fallen down into regardless of the outcome of the guards.

A further example where alternative structures are more difficult to read and modify:

block: if(/* guard */) {

  // prep work

  if(/* guard */) {
    break block;
  }

  // prep work

  if(/* guard */) {
    break block;
  }

  // real work
}

though usually I use a bare block and not an if.




回答2:


You can use labels before any statement block. This is maybe most commonly used for loops, but is perfectly valid elsewhere.




回答3:


Sarah Happy's answer is actually more correct than mine in showing that you can use break to break code blocks, in addition to loops, so I suggest looking at her answer.


That is indeed a label, which as you said is for For and While loops. It is valid elsewhere, but I'd like to add that you cannot use

goto name;

While goto is a reserved word, Java does not support goto, but it does support it in the form of labeled loops coupled with break and continue.

If you expanded your code sample to include a goto, like:

 name: if(true){
    //do something
  }
 goto name;

You'd get errors, saying both illegal start of expression and not a statement

Alternatively, if you tried to use continue with your label, but without a loop, like:

 name: if(true){
    //do something
  }
 continue name;

You'd get undefined label: name

So in terms of the compiler, having a label without a loop is ok, but it's pretty much worthless without a loop.




回答4:


Just like breaking a loop you might want to jump back or toward an if statement. Although whenever you start thinking about this, look into creating a new method instead.



来源:https://stackoverflow.com/questions/4904547/why-should-i-give-a-name-to-an-if-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!