lundi 4 juillet 2016

Java Style with-respect-to Multiple Returns, Used as "Guards"

is there a school of thought in the Java community with-repect-to using multiple returns in a method, in the manner shown below:

public SomeClass someMethod(int someValue) {
    if (someValue < SOME_CONSTANT) {
        return null;
    }

    SomeClass someClass = null;
    // and now, the body of the method that performs
    //   the heavy lifting
    return someClass;
}

I "grew up" under the mantra "single-entry-point, single-exit-point", but I can see how using simple guards could make code more readable/maintainable (i.e., eliminate levels of nesting). The "single-exit-point" version would look like...

public SomeClass someMethod(int someValue) {
    SomeClass someClass = null;

    if (someValue < SOME_CONSTANT) {
        // and now, the body of the method that performs
        //   the heavy lifting
    }
    return someClass;
}

This is, admittedly, somewhat of a trivial example, but I can see where more preconditions could result in greater nesting. Personally, I still would hold to "don't sprinkle returns throughout the method" for other purposes (i.e., only "return" as the result of a guard, or at the end of the method), but I'm wondering how the rest of the Java community feels.

Aucun commentaire:

Enregistrer un commentaire