45

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?

Jordan Noel
  • 220
  • 2
  • 4
  • 14
Daan Pape
  • 1,100
  • 1
  • 13
  • 25

6 Answers6

86

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).

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 6
    A single return statement was part of the code convention where I used to work. I find it leads to lots of nesting and much harder to read code. – brain May 29 '12 at 13:41
  • 3
    @brain: Indeed. It's usually the result of people taking on an idea without understanding the *reason* why it's a good idea in a certain context. – Jon Skeet May 29 '12 at 13:48
  • 1
    In the presence of exceptions, a single exit is just infeasable, as pretty much any piece of nontrivial code could raise one. It's better to go with the flow of the language here instead of forcing the code to behave according to some rules that might have made sense in a different environment/language. – Ulrich Eckhardt Sep 04 '13 at 13:27
  • @JonSkeet, look what you've done, [someone is using this answer](http://stackoverflow.com/questions/31327316/java-loops-compile-errors/31327747#31327747) to try to work around the Halting Problem. – Kelly S. French Jul 09 '15 at 21:08
10

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;
Mike Thomsen
  • 36,828
  • 10
  • 60
  • 83
  • 10
    Meh; it's generally better to write the most readable code, whatever that means for the number of return statements. For example, if you have a bunch of guard clauses, each (IMO) should return immediately on failure. – Dave Newton May 29 '12 at 13:38
  • As a side note, there is nothing to GC in this method, since there are no object allocations here. – Alexander Pavlov May 29 '12 at 13:38
  • Definitely agree with Dave -- I don't see why "where the method will exit" is of any importance per se. What matters is how easily you can follow the logic of the method. – Neil Coffey May 29 '12 at 13:50
4

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;
jn1kk
  • 5,012
  • 2
  • 45
  • 72
3

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.

Community
  • 1
  • 1
Óscar López
  • 232,561
  • 37
  • 312
  • 386
2

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.

Community
  • 1
  • 1
Insectatorious
  • 1,305
  • 3
  • 14
  • 29
2

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

for(int i=0; i<array.length; ++i){
    if(array[i] == valueToFind)
        return true;
}
Sameera R.
  • 4,384
  • 2
  • 36
  • 53