Someone on ##java asked about how to return a void value. This is a terrible question, but let’s look at it anyway, just because.
Here’s some example code they asked about, translated:
void foo(boolean bar) {
if(bar) {
return baz();
}
}
void baz() {
// do stuff here
}
The intent was to call baz() as a replacement for foo()‘s execution; the one with the question didn’t include code after the if() block, but further questions indicated that the remaining part of foo() was to be avoided.
There’s a lot of monstrosity here. The worst is “return baz();“, which won’t compile, and shouldn’t compile; void‘s whole purpose is to avoid being put on the call stack, so “return void” makes no sense.
One way to rewrite this code is obvious:
void foo(boolean bar) {
if(bar) {
baz();
return;
}
// extra code goes here,
// not to be executed if bar is true
}
void baz() {
// do stuff here
}
This calls baz() and terminates the method execution immediately after. You could also do something else that’s obvious:
void foo(boolean bar) {
if(bar) {
baz();
} else {
// extra code goes here
}
}
This has the advantage of a single termination point for the method. From “Code Complete:”
17.1 return
Minimize the number of returns in each routine. It’s harder to understand a routine if, reading it at the bottom, you’re unaware of the possibility that it returned somewhere above.
Use a return when it enhances readability. In certain routines, once you know the answer, you want to return it to the calling routine immediately. If the routine is defined in such a way that it doesn’t require any cleanup, not returning immediately means that you have to write more code.
(Content copied shamelessly from an excellent answer on StackOverflow.)