dimanche 31 mai 2020

Else after return from first part of an if statement

The implementation of library's BigInteger.gcd(...) method begins with these statements:

public BigInteger gcd(BigInteger val) {
    if (val.signum == 0)
        return this.abs();
    else if (this.signum == 0)
        return val.abs();
    ...
}

What is the purpose of the else keyword in this case? Is it just a remnant of an old code that the programmer has forgotten to delete or it impacts performance in some way?

I understand that, semantically, the versions with and without else are identical in this particular case. Quite often, however, I face the choice between

<Some method signature>(...) {
    if (...) {
        <Short branch>
        return ...;
    } else {
        <Long branch>
        return ...;
    }
}

and

<Some method signature>(...) {
    if (...) {
        <Short branch>
        return ...;
    }
    <Long branch>
    return ...;
}

Which option is better in terms of performance (note that this question is Java-specific)? If performance is almost identical in both cases, which one is better in terms of readability?

Aucun commentaire:

Enregistrer un commentaire