Multiple return statements
Some programmers find that, occasionally, some methods become clearer if multiple return statements are used, instead of the usual single point of exit.
This technique can be easily abused, and should be used with care. It's mainly used to replace nested if structures.
Multiple return statements seem to work well for "guard code" at the beginning of a method, in which the main body of the method is executed only if certain conditions are satisfied.
Example
Here, equals has multiple return statements, since
a successful test implies that further comparison is redundant. The alternative
is to use multiple if statements, which some would find less legible.
import java.util.*; public final class Auto { public boolean equals(Object aThat) { if (this == aThat) return true; if (!(aThat instanceof Auto)) return false; Auto that = (Auto)aThat; return EqualsUtil.areEqual(this.fName, that.fName) && EqualsUtil.areEqual(this.fNumDoors, that.fNumDoors) && EqualsUtil.areEqual(this.fOptions, that.fOptions) && EqualsUtil.areEqual(this.fGasMileage, that.fGasMileage) && EqualsUtil.areEqual(this.fColor, that.fColor) && Arrays.equals(this.fMaintenanceChecks, that.fMaintenanceChecks) ; } //..elided // PRIVATE private String fName; private int fNumDoors; private List<String> fOptions; private double fGasMileage; private String fColor; private Date[] fMaintenanceChecks; }
See Also :
Would you use this technique?