Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 733
Carasel Avatar asked Dec 19 '12 09:12

Carasel


People also ask

What is break in for loop?

break terminates the execution of a for or while loop. Statements in the loop after the break statement do not execute. In nested loops, break exits only from the loop in which it occurs.

Can we use break in if loop?

The break statement ends the loop immediately when it is encountered. Its syntax is: break; The break statement is almost always used with if...else statement inside the loop.

How do you break a loop in a procedure?

To exit the current iteration of a loop, you use the BREAK statement. In this syntax, the BREAK statement exit the WHILE loop immediately once the condition specified in the IF statement is met. All the statements between the BREAK and END keywords are skipped.

Can we use break in if without loop?

Normally you can't. You can only use return; to discontinue code execution in an if statement.


3 Answers

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;
   }
}
like image 175
Amber Avatar answered Oct 11 '22 15:10

Amber


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.

like image 45
Thirler Avatar answered Oct 11 '22 14:10

Thirler


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;
}
like image 22
jdtaylor Avatar answered Oct 11 '22 15:10

jdtaylor