samedi 29 août 2020

Simplifying Java IF-ELSE

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?

Aucun commentaire:

Enregistrer un commentaire