简体   繁体   中英

Double not in if condition - best practice?

I'm still kind of a newbie so your wisdom and advice would be appreciated.

I've got a tricky if condition and I'm not sure I'm doing this correctly.

if(!conditionOne && conditionTwo){
  //do nothing
} else {
  //do something
}

I hate having an empty code block for the if but I'm not sure of a better way to do this. This seems like the least amount of code without making it less simple with something like

if(!(!conditionOne && conditionTwo)){  

This just looks odd to me but maybe this is better?

Or

if((!conditionOne && !conditionTwo) || (conditionOne && conditionTwo) || (conditionOne && !conditionTwo){

That seems more complicated to me.

conditionOne      conditionTwo          Outcome
False              True                  Do nothing
False              False                 Do something
True               True                  Do something
True               False                 Do something

What would be the best way to implement this?

By De-Morgan's law , you're looking for

if(conditionOne || !conditionTwo) {
    //do something
}

You should check out De Morgan's Laws . It covers some important concepts. For example:

!(a && b) is equivalent to (!a || !b)

and similarly

!(a || b) is equivalent to (!a && !b)

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