Short form for Java If Else statement

userit1985 picture userit1985 · Feb 2, 2017 · Viewed 7.4k times · Source

I have a method which checks for nulls. Is there a way to reduce the number of lines in the method? Currently, the code looks "dirty":

private int similarityCount (String one, String two) {

    if (one == null && two == null) {
        return 1;
    } else if (one == null && two != null) {
        return 2;
    } else if (one != null && two == null) {
        return 3;
    } else {
        if(isMatch(one, two))
             return 4;
        return 5;
    }

}

Answer

Manh Le picture Manh Le · Feb 2, 2017
private int similarityCount (String one, String two) {

    if (one == null && two == null) {
        return 1;
    } 

    if (one == null) {
        return 2;
    } 

    if (two == null) {
        return 3;
    } 

    if (isMatch(one, two)) {
        return 4;
    }
    return 5;
}