简体   繁体   中英

What is the best way to write better/cleanish IF statements when you have multiple conditions?

I would like to refactor a few if statements I've encountered in some legacy code, to make them easier to read.

For example:

if (condition1 || condition2 || condition3 || condition4 || condition5 || condition6 || condition7) 

I thought about maybe store the long condition list in a variable, give it a descriptive name and use that variable name in the if statement.

Having readable code is above all a question of presentation

you can do

if ( (condition1)
  || (condition2)
  || (condition3)
  || (condition4)
  || (condition5)
  || (condition6)
  ) {
    // something to do...
  }

or:
(dark and obscure method reserved for members of the sect of demonic coders)

switch (true) {
  case (condition1):
  case (condition2):
  case (condition3):
  case (condition4):
  case (condition5):
  case (condition6):
    // something to do...
    break;
 }

[edit]
You can also use an indent to show the hierarchy of conditions:

if ( (condition1)
  || (condition2)
  || ( (condition3-1)
    && (condition3-2)
    && (condition3-3)
    )
  || (condition4)
  || (condition5)
  || (condition6)
  ) {
    // something to do...
  }

I think the good approach in this case is Consolidate Conditional Expression. You can combine all conditions in one function.

function isConditionsCorrect() {
    return (condition1)
        || (condition2)
        || (condition3)
        || (condition4)
        || (condition5)
        || (condition6);
} 

if (isConditionsCorrect()) return 0;

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