Simplifying Java IF-ELSE

Viewed 197

Imagine there is an "if statement" with n conditions:

if (a == b || x == '0' || z == '1' .... || s == 'e') {      // < n conditions 
    result = do_something(); 
}

Can this be re-written as below :

switch (??) {
   case a == b:
   case x == '0':
   case z == '1';
   ...
   case s == 'e':
        result = do_something();
        break;
   default:
        break;
}

It feels more readable, and less cumbersome than multiple conditions separated by OR/AND operators. If another condition needs to be added then we can just add another case.

Is this possible? If yes, then please share an implementation.
OR
Is the original "if statement" itself a result of bad coding and hence, should be taken as a hint that the entire code needs to be revisited and improved?

2 Answers

The short answer is no you can not and you also should not. You can simply format it in a nice way:

if (a == b 
   || x == '0' 
   || (z == '1' &&  a == 'e')
   || s == 'e') {      
    result = do_something(); 
}

The long answer is you could but it would be messy and unclear!

In Java (and most other languages) switch is for 'switching' over an enumeration. So you can not switch with boolean expressions like x == b. Not even simple things like this work:

 //NOT REAL JAVA CODE
 switch (true) {
        case true:
            Sytem.out.println("true");
            break;
        case false:
            Sytem.out.println("false");
            break;
    }

So the only way left would be to create a repsentative enum... Wich is a bad Idea for all cases i can think of.

If an if really escalates consider the following ideas for simplification

  • comment more
  • Use loops instead
  • Use more Ifs instead
  • Use a truth table to simplify the if

The switch statement is a good candidate for cases when we have a limited number of options in a pre-defined set (eg: days of the week). We can't compare all the types of objects and primitives in the switch statement. We can't pass the null value as an argument to a switch statement. If we do it, the program will throw NullPointerException.

You will find more such things if you search. So, just for sake of readability, don't change if statement to switch case. You can make if statement more readable by well formatting, adding comments on if block mentioning the condition use, using nested if.

Related