0

I've seen this in java at least and I'm pretty sure it exists in other languages as well, but I'm referring to code like this

label: {
        if (someStatment) {
            break label;
        }
        if (someOtherStatemnt) {
            break label;
        }
        return a + b;
    }

or even:

int a = 0;
label: {
   for(int i=0;i<10; i++){
        if (a>100) {
            break label;
        }

        a+=1;
    }

Now I'm wondering what are the reason people use labels? It doesn't really seem like a good idea. I was just wondering if anyone had a real world scenario where this made sense to use this type of structure.

dbarnes
  • 1,803
  • 3
  • 17
  • 31

1 Answers1

2

Labelled breaks come into their own when loops and case statements are nested. Here's an example in Java, abridged, of something I wrote in the past 6 months:

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
}

The data structures provided by the API that I was using are a little gnarly, hence the complicated nesting.

You can always set a flag to control your loop exits, but I find that judicious use of labelled breaks makes for more concise code.

Post script: Furthermore, if my code inspection team and or shop coding standards were to proscribe labels, I would gladly rewrite to be in conformance.

David Gorsline
  • 4,933
  • 12
  • 31
  • 36