Coding style 标签在编程中的使用
我至少在java中看到过这一点,我很确定它也存在于其他语言中,但我指的是这样的代码Coding style 标签在编程中的使用,coding-style,Coding Style,我至少在java中看到过这一点,我很确定它也存在于其他语言中,但我指的是这样的代码 label: { if (someStatment) { break label; } if (someOtherStatemnt) { break label; } return a + b; } 甚至: int a = 0; label: { for(int i=0;
label: {
if (someStatment) {
break label;
}
if (someOtherStatemnt) {
break label;
}
return a + b;
}
甚至:
int a = 0;
label: {
for(int i=0;i<10; i++){
if (a>100) {
break label;
}
a+=1;
}
inta=0;
标签:{
对于(int i=0;i100){
打破标签;
}
a+=1;
}
现在我想知道人们使用标签的原因是什么?这似乎不是个好主意。我只是想知道是否有人在现实世界中使用这种类型的结构是有意义的。当循环和case语句嵌套时,带标签的中断就会出现。下面是我在过去6个月里用Java编写的一个节略示例:
Node matchingNode = null; //this is the variable that we want to set
Iterator<Resource> relatedNodes = tag.find();
outer:
while (relatedNodes.hasNext() && matchingNode == null) {
Node node = relatedNodes.next().adaptTo(Node.class);
if (honorIsHideInNav && NodeUtils.isHideInNav(node)) {
//we don't want to test this node
continue; //'continue outer' would be equivalent
}
PropertyIterator tagIds = node.getProperties("cq:tags");
while (tagIds.hasNext()) {
Property property = tagIds.nextProperty();
Value values[] = property.getValues();
for (Value value : values) {
String id = value.getString();
if (id.equals(tag.getTagID())) {
matchingNode = node; //found what we want!
break outer; //simply 'break' here would only exit the for-loop
}
}
}
}
if (matchingNode == null) {
//we've scanned all of relatedNodes and found no match
}
节点匹配Node=null//这是我们要设置的变量
迭代器relatedNodes=tag.find();
外部:
while(relatedNodes.hasNext()&&matchingNode==null){
Node Node=relatedNodes.next().adapto(Node.class);
if(荣誉isHideInNav&&NodeUtils.isHideInNav(节点)){
//我们不想测试此节点
continue;/“continue outer”将等效
}
PropertyIterator tagIds=node.getProperties(“cq:tags”);
while(tagIds.hasNext()){
Property=tagIds.nextProperty();
Value values[]=property.getValues();
用于(值:值){
String id=value.getString();
if(id.equals(tag.getTagID())){
matchingNode=node;//找到了我们想要的!
break outer;//在这里简单地“break”只会退出for循环
}
}
}
}
if(matchingNode==null){
//我们已扫描所有相关节点,但未找到匹配项
}
我使用的API提供的数据结构有点粗糙,因此嵌套比较复杂
您总是可以设置一个标志来控制循环出口,但我发现明智地使用带标签的中断可以使代码更加简洁
Post script:此外,如果我的代码检查团队和/或商店编码标准禁止使用标签,我会很乐意重写以符合要求。相关:这只是goto的一个更丑陋的版本。我诚实地阅读了数千行java代码,从未见过使用过标签。