简体   繁体   中英

Simplify if statement with multiple conditions

i am stuck to simplify such an if statement. The if statement in my Project looks somehow like this, but alitle bit more complex. There i have more if and if else conditions with multiple OR conditions.

private int testMethod(int a, char b, String s, float f, double d, TestClass testClass){
    if (a == 2 || s.equals("testString") || f == 5 || d == 4 || testClass.getName().equals("testName")){
        return 1;
    }else if (a == 3 || f == 10 || d == 1){
        return 2;
    }else {
        return 3;
    }
}

is there any way to simplify such an if statement? thanks!

If you can simplify this you can try this. But I think that your code needs in refactoring:)

private int testMethod(int a, char b, String s, float f, double d, TestClass testClass){
    return isaBoolean(a, s, f, d, testClass) ? 1 : isaBoolean(a, f, d) ? 2 : 3;
}

private boolean isaBoolean(int a, float f, double d) {
    return a == 3 || f == 10 || d == 1;
}

private boolean isaBoolean(int a, String s, float f, double d, TestClass testClass) {
    return a == 2 || s.equals("testString") || f == 5 || d == 4 || testClass.getName().equals("testName");
}

You can try to check with some boolean logic with the real conditions, but if you have a condition that requires f == 5 or d == 4 there's no quicker way to do it than f == 5 || d == 4f == 5 || d == 4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM