简体   繁体   中英

How to simplify IF statements with many conditions

I have often come across codes samples as below.

if(X == x && A == a){
}
else if (X == y && A == b){
}
else if (X == z && A == c){
}
else if (X == zz && A == d){
}

OR sometimes conditions like this

if(X == x && A == a){
}
else if (X == x && A == b){
}
else if (X != x &&  A == a){
}
else if (X !=x  && A == b){
}

Are there more efficient and better ways to refactor this code in terms of efficiency, code clearness and Understandability?

You can wrap you statement in a function, it will be a bit cleanner :

if(X == x && A == a){
  do_A();
}
else if (X == x && A == b){
  do_B();
}
else if (X != x &&  A == a){
  do_C()
}
else if (X !=x  && A == b){
  do_D()
}

would become :

const doSomething = () => {
  if (X == x && A == a) return do_A();
  if (X == x && A == b) return do_B();
  if (X != x &&  A == a) return do_C();
  if (X !=x  && A == b) return do_D();
};

doSomething();

You can use switch statement, like this: switch(expression) { case x: // code block break; case y: // code block break; default: // code block } however you will not have a much more efficient code as mentioned by @jcubic

A possible solution would be to use a switch-case statement like so:

switch(X + "|" + A) {
    case x + "|" + a:
        ...
        break;
    case y + "|" + a:
        break;
    case z + "|" + c:
        break;
    case zz + "|" + d:
        break;
}

I don't know if you think this writing style looks better to you, but it is less efficient than the one you proposed in your question since you have to join strings before comparing them.

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