What's the difference between these 2 ifs?

if(loadFactor != null && !(trialExists(loadFactor))

and

if(!(loadFactor == null || trialExists(loadFactor))

I was asked in a review to make 1st if changed to 2nd. How does it make any difference.

Jon Skeet
people
quotationmark

There's no difference.

In both cases:

  • If loadFactor is null, trialExists(loadFactor) won't be evaluated, and the condition will be false, so it won't enter into the if body
  • Otherwise, trialExists(loadFactor) will be evaluated, and the condition will be the opposite of the result - so it will only enter the body of the if statement if trialExists(loadFactor) returns false

This is because both && and || are short-circuiting:

  • If the first operand of && is false, the second operand isn't evaluated and the result is just false
  • If the first operand of || is true, the second operand isn't evaluated and the result is just true

Personally I prefer the first piece of code to the second. It reads to me as "If we've got a load factor, and there's no trial for it." The second piece of code is more obscure, because the inner condition is "if we don't have a load factor or it's an existing trial" - which isn't a particularly natural condition to express, in my view.

people

See more on this question at Stackoverflow