ラベル付きブレークは、ループと 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
}
私が使用していた API によって提供されるデータ構造は少しぎこちなく、複雑な入れ子になっています。
フラグを設定してループの終了を制御することはいつでもできますが、ラベル付きのブレークを適切に使用すると、コードがより簡潔になります。
追記:さらに、私のコード検査チームやショップのコーディング標準がラベルを禁止する場合は、準拠するように喜んで書き直します。