Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return in for loop or outside loop

Today, someone attended me to bad use of the return keyword in Java. I had written a simple for loop to validate that something is in an array. Supposing array is an array of length n, this was my code:

for (int i = 0; i < array.length; ++i) {
    if (array[i] == valueToFind) {
        return true;
    }
}
return false;

Now someone told me that this is not very good programming because I use the return statement inside a loop and this would cause garbage collection to malfunction. Therefore, better code would be:

int i = 0;
while (i < array.length && array[i] != valueToFind) {
    ++i;
}
return i != array.length;

The problem is that I can't come up with a proper explenation of why the first for loop isn't a good practice. Can somebody give me an explanation?

like image 554
Daan Pape Avatar asked May 29 '12 13:05

Daan Pape


People also ask

Can you use return in a for loop?

The return statement is useful because it saves time and makes the program run faster by returning the output of method without executing unnecessary code and loops. It is good practice to always have a return statement after the for/while loop in case the return statement inside the for/while loop is never executed.

What happens when a return statement inside a for loop is executed?

What happens when a return statement inside a for loop is executed? The program immediately quits the current method. FALSE; A class's instance data are declared in the class but NOT inside any method. Variables declared in a method are local to that method and can only be used in that method.

Can we use return in for loop in Python?

Using a return inside of a loop will break it and exit the function even if the iteration is still not finished. In some cases we need to break the loop if some conditions are met. However, in your current code, breaking the loop before finishing it is unintentional.

Can we use return in for loop in C?

The answer is yes, it will return.


6 Answers

Now someone told me that this is not very good programming because I use the return statement inside a loop and this would cause garbage collection to malfunction.

That's incorrect, and suggests you should treat other advice from that person with a degree of skepticism.

The mantra of "only have one return statement" (or more generally, only one exit point) is important in languages where you have to manage all resources yourself - that way you can make sure you put all your cleanup code in one place.

It's much less useful in Java: as soon as you know that you should return (and what the return value should be), just return. That way it's simpler to read - you don't have to take in any of the rest of the method to work out what else is going to happen (other than finally blocks).

like image 169
Jon Skeet Avatar answered Sep 26 '22 09:09

Jon Skeet


Now someone told me that this is not very good programming because I use the return statement inside a loop and this would cause garbage collection to malfunction.

That's a bunch of rubbish. Everything inside the method would be cleaned up unless there were other references to it in the class or elsewhere (a reason why encapsulation is important). As a rule of thumb, it's generally better to use one return statement simply because it is easier to figure out where the method will exit.

Personally, I would write:

Boolean retVal = false;
for(int i=0; i<array.length; ++i){
    if(array[i]==valueToFind) {
        retVal = true;
        break; //Break immediately helps if you are looking through a big array
    }
}
return retVal;
like image 33
Mike Thomsen Avatar answered Sep 25 '22 09:09

Mike Thomsen


There have been methodologies in all languages advocating for use of a single return statement in any function. However impossible it may be in certain code, some people do strive for that, however, it may end up making your code more complex (as in more lines of code), but on the other hand, somewhat easier to follow (as in logic flow).

This will not mess up garbage collection in any way!!

The better way to do it is to set a boolean value, if you want to listen to him.

boolean flag = false;
for(int i=0; i<array.length; ++i){
    if(array[i] == valueToFind) {
        flag = true;
        break;
    }
}
return flag;
like image 32
jn1kk Avatar answered Sep 25 '22 09:09

jn1kk


Some people argue that a method should have a single point of exit (e.g., only one return). Personally, I think that trying to stick to that rule produces code that's harder to read. In your example, as soon as you find what you were looking for, return it immediately, it's clear and it's efficient.

Quoting the C2 wiki:

The original significance of having a single entry and single exit for a function is that it was part of the original definition of StructuredProgramming as opposed to undisciplined goto SpaghettiCode, and allowed a clean mathematical analysis on that basis.

Now that structured programming has long since won the day, no one particularly cares about that anymore, and the rest of the page is largely about best practices and aesthetics and such, not about mathematical analysis of structured programming constructs.

like image 42
Óscar López Avatar answered Sep 26 '22 09:09

Óscar López


The code is valid (i.e, will compile and execute) in both cases.

One of my lecturers at Uni told us that it is not desirable to have continue, return statements in any loop - for or while. The reason for this is that when examining the code, it is not not immediately clear whether the full length of the loop will be executed or the return or continue will take effect.

See Why is continue inside a loop a bad idea? for an example.

The key point to keep in mind is that for simple scenarios like this it doesn't (IMO) matter but when you have complex logic determining the return value, the code is 'generally' more readable if you have a single return statement instead of several.

With regards to the Garbage Collection - I have no idea why this would be an issue.

like image 24
Insectatorious Avatar answered Sep 25 '22 09:09

Insectatorious


Since there is no issue with GC. I prefer this.

for(int i=0; i<array.length; ++i){
    if(array[i] == valueToFind)
        return true;
}
like image 43
Sameera R. Avatar answered Sep 26 '22 09:09

Sameera R.