I believe the idea of a single exit point for functions comes from the 70’s. A function used to have only one exit point, a single return statement. I still see some developers doing this but it’s not a good idea. As soon as you have found what you were looking for, just get out the function.

The old style:

public int someMethod(String input) {
     int code = 0;
     if (someCondition(input))
         code = 1;
     else if (someOtherCondition(input))
         code = 2
     return code;
}

Improved: returning the value as soon as it’s found:

public int someMethod(String input) {
     if (someCondition(input))
         return 1;
     if (someOtherCondition(input))
         return 2;
     return 0;
}

The second example is not only shorter but also less exposed to defects. In the first example, if for some reason I forgot the “else” and the second condition applies, I’d be returning the wrong value.

The reasons to return as soon as possible are:

  • Code is usually more simple
  • The likelihood of future defects is lower