Search code examples
if-statementstandards

If-else vs if not-if


According to a lead at work, the distinction between

if (invalid) {
   ...some code
}

if (!invalid) {
  ...some code
}

and

if (invalid) {
  ...some code
} else {
  ...some code
}

can be interpreted as a style choice. I was wondering where people draw the line and what you would consider this.

PS: Yes, I know negations should not be the 'nominal' case for if statements. Please ignore that as I was trying to replicate exactly the code in question that prompted the discussion.


Solution

  • Not only is there redundancy here, but depending on the language, there can also be a difference in correctness/validity. Consider this C# code:

    int value;
    bool condition = DateTime.UtcNow.Second < 30;
    if (condition)
    {
        value = 10;
    }
    else            
    {
        value = 20;
    }
    // No problem, value is definitely assigned
    Console.WriteLine(value);
    

    That's entirely valid. But if we write it in the redundant style, we'll get a compile-time error:

    int value;
    bool condition = DateTime.UtcNow.Second < 30;
    if (condition)
    {
        value = 10;
    }
    if (!condition)
    {
        value = 20;
    }
    // error CS0165: Use of unassigned local variable 'value'
    Console.WriteLine(value);
    

    The same would be true in Java, and I suspect in many other languages as well. The compiler can take account of the fact that in if/else, execution will flow into exactly one of those branches. In the "two if statements" style, the language rules don't make that guarantee.