mercredi 25 septembre 2019

Java: How to replace multiple nested if-else statements with a more maintainable design

I need to execute a different action doAction1(), doAction2() ... depending on the value and/or type of some variables and return value of some functions. All combinations could be possible, in principle.

The quick solution is to test all combinations within nested if-else statements but the resulting code is quite ugly and difficult to maintain and extend (in case for instance I have new conditions to test for). I include some sample code below. I am using Java SE 8:

public static boolean myFunct () {
    return true;  // hardcoded, it could also return false
}

public static void main(String[] args) {

    int x = 1;  // hardcoded, it could also be =2
    Object o = new String();  // hardcoded, it could also be an Integer

    // here I begin to test to decide which action to execute
    if (x == 1) {
        if (o instanceof String) {
            if ( myFunct() ) {
                // do this if x==1 AND o is a String AND myFunct() returns true
                doAction1();  
            }
            else {
                doAction2();
            }
        }
        else if (o instanceof Integer) {
            if ( myFunct() ) {
                doAction3();
            }
            else {
                doAction4();
            }
        }
    }
    else if (x == 2) {
        if (o instanceof String) {
            if ( myFunct() ) {
                doAction5();
            }
            else {
                doAction6();
            }
        }
        else if (o instanceof Integer) {
            if ( myFunct() ) {
                doAction7();
            }
            else {
                doAction8();
            }
        }
    }
}

private static void doAction8() {
    // do some work...
}

private static void doAction7() {
    // do some work...
}

private static void doAction6() {
    // do some work...
}

private static void doAction5() {
    // do some work...
}

private static void doAction4() {
    // do some work...
}

private static void doAction3() {
    // do some work...
}

private static void doAction2() {
    // do some work...
}

private static void doAction1() {
    // do some work...
}

I read about a RuleEngine design pattern that could elegantly apply to this kind of cases and replace the nested if-else statements but cannot really find how to implement it for my case.

Thank you in advance for your recommendations.

Aucun commentaire:

Enregistrer un commentaire