amukhachov
amukhachov

Reputation: 5900

How to rewrite java code without use of labels?

categoryCheck: {
        for (String allowedCategory : allowedCategories) {
            if (evt.getLoggerName().startsWith(allowedCategory)) {
                break categoryCheck;
            }
        }
        return false;
    }

Is it any ideas how to rewrite this code without using labels and without considerable increasing of it?

Upvotes: 1

Views: 260

Answers (4)

NPE
NPE

Reputation: 500257

Here is a direct equivalent using a boolean flag:

    boolean found = false;
    for (String allowedCategory : allowedCategories) {
        if (evt.getLoggerName().startsWith(allowedCategory)) {
            found = true;
            break;
        }
    }
    if (!found) {
        return false;
    }
    // ...the rest of the method's code...

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533492

You can use a flag.

boolean found = false;
for (String allowedCategory : allowedCategories) {
    if (evt.getLoggerName().startsWith(allowedCategory)) {
        found = true;
        break;
    }
}
if(!found) 
    return false;

Upvotes: 1

Graham Borland
Graham Borland

Reputation: 60681

boolean matched = false;

for (String allowedCategory : allowedCategories) {
    if (evt.getLoggerName().startsWith(allowedCategory)) {
        matched = true;
        break;
    }
}

if (!matched)
    return false;

// else continue with the rest of the code

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500065

I'd probably put it into its own method:

// I've guessed at the types...
public boolean isCategoryAllowed(Event evt, Iterable<String> allowedCategories) {
    for (String allowedCategory : allowedCategories) {
        if (evt.getLoggerName().startsWith(allowedCategory)) {
            return true;
        }
    }
    return false;
}

Then change the calling code to simply call the method:

if (!isCategoryAllowed(evt, allowedCategories)) {
    return false;
}

Upvotes: 6

Related Questions