Java Reference
In-Depth Information
Listing 5-21. Using return to stop processing
public String getAuthorForDetective (String detective) {
if(detective.equals("Sam Spade")) {
return "Dashiell Hammett";
}
if (detective.equals("Sherlock Holmes")) {
return "Sir Arthur Conan Doyle";
}
if (detective.equals("Charlie Chan")) {
return "Earl Derr Biggers";
}
return "Unknown author";
}
As you can see in this example, as soon as we find the author that matches the fictional character,
we stop looking and return the name of the author. If all else fails, we admit to not knowing the name of
the author. We don't need else statements because each if statement has a return statement; at each if
statement, we stop processing if we get a match and continue processing if we don't get a match, so else
is needless syntax. This idiom is common in Java programs. It works especially well when you can order
your matches by likelihood. That way, you can often do as little processing as possible, which makes for
a handy bit of optimization. For example, if you happen to code on behalf of the Sherlock Holmes
Memorial Library (if there is such a thing), you'd put the “Sherlock Holmes” match at the top.
Let's consider a similar example in Listing 5-22 for a method that returns void .
Listing 5-22. Using return with no values
public void printAuthorForDetective (String detective) {
if(detective.equals("Sam Spade")) {
System.out.println("Dashiell Hammett");
return;
}
if (detective.equals("Sherlock Holmes")) {
System.out.println("Sir Arthur Conan Doyle");
return;
}
if (detective.equals("Charlie Chan")) {
System.out.println("Earl Derr Biggers");
return;
}
System.out.println("Unknown author");
}
Again, the return statements stop further processing within the method and return processing to
the code that called the method. If we don't have the return statements, the method prints whatever
match it found (if any) and then prints, “Unknown author.” So, in addition to causing needless
processing, leaving out the return statements also creates a bug. We don't need a return statement after
the last statement because the method implicitly returns after the last instruction.
Search WWH ::




Custom Search