Carasel
Carasel

Reputation: 2871

Break in a method called from a loop

I'm refactoring a very large method with a lot of repetition in it.

In the method there are many while loops which include:

    if ( count > maxResults){
        // Send error response
        sendResponse(XMLHelper.buildErrorXMLString("Too many results found, Please refine your search"), out, session);
        break;

I want to extract this as a method, because it happens 3 times in this one method currently, but when I do so I get an error on the break as it is no longer within a loop. The problem is that it is still necessary to break out of the while loops, but only when the maximum number of results are reached.

Any suggestions?

Upvotes: 5

Views: 991

Answers (5)

Thirler
Thirler

Reputation: 20760

This is impossible to do directly.

Most often you want to break because you have found the solution and no longer have to search. So indicate in the called function that there is/was success, for instance by returning a result or a boolean to indicate success. And if the function returns success, then break.

Upvotes: 3

Amber
Amber

Reputation: 1249

Suppose the method is :

public boolean test(int count, int maXResult) {
 if ( count > maxResults) {
        // Send error response
        sendResponse(XMLHelper.buildErrorXMLString("Too many results found, Please refine your search"), out, session);
        return true;
        }
return false;
}

Call method from loop as :

while(testCondition) {
    if (test(count, maxResults)) {
    break;
   }
}

Upvotes: 3

jdtaylor
jdtaylor

Reputation: 334

If it is now within a method instead of the while loop have it return a value and then break based on that.

i.e.

public bool refactoredMethod(parameters)
{
    if ( count > maxResults){
    // Send error response
    sendResponse(XMLHelper.buildErrorXMLString("Too many results found, Please refine your     search"), out, session);

    return true;
    }

    return false;
}

Upvotes: 1

cowls
cowls

Reputation: 24334

As Thriler says you cant do it directly. You could extract part of it to the method and do something like:

if(isTooManyResults(count)) { break; }

Obviously your isTooManyResults method would need to return true if there are too many results and false otherwise

Upvotes: 0

Jj Tuibeo
Jj Tuibeo

Reputation: 773

Try to break the loop in the method using return;

Upvotes: 0

Related Questions