Search code examples
javaif-statementanti-patterns

How can i reduce an Arrow head type if statement with 3 different else`s?


im going to try to explain myself in the best way possible, i have a method that looks like this:

if(condition1)
    if(condition2) {
        if(condition3) {
                      //do something if the 3 conditions are met
        }
        else {
              //do something if condition 3 is NOT met      
        }   
    }
    else{
                //do something if condition 2 is NOT met
        }               
else{
        //do something if condition 1 is NOT met
}

I have been having trouble expanding and maintaining this code and i have seen ways to prevent this anti-pattern from happening but the solutions only focused on how to refactor the code so the if-blocks came out more clean, but i havent seen any solutions aiming to clean out diferent else blocks and even less solutions that focus on else-blocks which have diferent functionality.

I'd be glad if any of you could enlight me on how to tackle this problem. Looking forward to your responses and thank you in advance :).

Edit: i know there are a lot of ways to arreange these conditionals what im asking is the most correct way to do it so the code is a little easier to maintain


Solution

  • It heavily depends on the type of conditions. Without further knowledge of the code logic, you could look at early returns, which could look something like this:

    if (not condition1) {
        //do something if condition 1 is NOT met
    
        return; //only required if language does not support else if
    }
    else if (not condition2) {
        //do something if condition 2 is NOT met
    
        return; //only required if language does not support else if
    }
    else if (not condition3) {
        //do something if condition 3 is NOT met
    
        return; //only required if language does not support else if
    }
    else {
        //do something if all three conditions are met
        
        return;
    }