Search code examples
c#javacoding-style

Is it considered readable to call methods inside the IF condition?


Is this way of writing IF conditions considered good coding style in Java and C# languages or not?

if (checkIfIdInFirstRange()){
    //call Range1 handling method
}else if(checkIfIdInSecondRange()){
    //call Range2 handling method
}else{
    //call error handling method
}

I'm wondering about the method inside the IF condition itself, or would it be better to make it like:

int idInRange = getIdInRange();
//handle isInRange

Solution

  • I think this is fine.

    Even better is if you phrase your methods like a question, or flows with the if statement

    if (thisConditionIsTrue()){
        // Do this
    }elseif(anotherConditionIsTrue()){
        // Do this instead
    }elseif(isThisParameterOkay(someParameter)){
        // Yeh do this
    }
    

    Some hardcore purists will even say that if you have > 3 levels of indentation, your method is too nested and should be split into smaller methods.