mercredi 12 octobre 2016

Elegant way to return a value inside an if [on hold]

Imagine you want to write a simple method, which take a String argument named "foo". The method should return the int "1" if foo equals "toto" and "2" in the others cases. What is the best way to write this method without using a ternary expression ?

I have several solutions but can't decide by myself which one is the best in Java.

Solution 1 :

public int method1(String foo){
    if("toto".equals(foo){
       return 1;
    }
    return 2;
}

Solution 2 :

public int method2(String foo){
    if("toto".equals(foo){
       return 1;
    } else {
        return 2;
    }
}

Solution 3 :

public int method3(String foo){
    int result = 2;
    if("toto".equals(foo){
       result = 1;
    }
    return result;
}

Solution 4 :

public int method4(String foo){
    int result = 0;
    if("toto".equals(foo){
       result = 1;
    } else {
       result = 2;
    }
    return result;
}

Any ohter idea ?

Remember, I search a solution without ternary condition.

Thanks,

Aucun commentaire:

Enregistrer un commentaire