Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If else redundant code to a simpler form

How to represent the following if else condition in a better way?

        if ((!StringUtils.isEmpty(A) && !StringUtils.isEmpty(B)) {
            System.out.println("Case 1");
        } else if ((!StringUtils.isEmpty(A) && StringUtils.isEmpty(B)) {
            System.out.println("Case 2");
        } else if ((StringUtils.isEmpty(A) && !StringUtils.isEmpty(B)) {
            System.out.println("Case 3");
        } else if ((StringUtils.isEmpty(A) && StringUtils.isEmpty(B)) {
            System.out.println("Case 4");
        } else {
            System.out.println("End");
        }
like image 884
intruder Avatar asked Jan 29 '23 10:01

intruder


1 Answers

Assuming Case 1 and Case 4 are not supposed to have the same condition, which eliminates the possibility of End, you can do this:

if (StringUtils.isEmpty(A)) {
    if (StringUtils.isEmpty(B)) {
        System.out.println("Case 4");
    } else {
        System.out.println("Case 3");
    }
} else {
    if (StringUtils.isEmpty(B)) {
        System.out.println("Case 2");
    } else {
        System.out.println("Case 1");
    }
}

Or you can use a switch statement, with a little bit-math:

switch ((StringUtils.isEmpty(A) ? 2 : 0) | (StringUtils.isEmpty(B) ? 1 : 0)) {
    case 0: // !empty(A) & !empty(B)
        System.out.println("Case 1");
        break;
    case 1: // !empty(A) & empty(B)
        System.out.println("Case 2");
        break;
    case 2: // empty(A) & !empty(B)
        System.out.println("Case 3");
        break;
    default: // empty(A) & empty(B)
        System.out.println("Case 4");
}
like image 178
Andreas Avatar answered Feb 02 '23 10:02

Andreas