Reverse Conditional

Inverts the logic in a conditional statement and swaps the if and else blocks.

Purpose

  • This refactoring can make some expressions easier to read by inverting them and swapping the if and else blocks.
  • Reverse conditional is also useful when an if statement has a matching else block that terminates with a call to exit the method (e.g., return in C#). By swapping the if and else blocks, the if block now ends with the call to exit the method, which means the else keyword is now redundant. The redundant else keyword and its block delimiters can now be removed, which effectively un-indents the code inside. This reduces the nesting of the code that typically serves as the essence of the method and improves readability.

Availability

Available from the context menu or via shortcuts:

  • when the edit cursor, or caret is on the if keyword of an if statement which has a corresponding else block.

Example

if (A)
    return B;
else
    return C;
If A Then
    Return B
Else
    Return C
End If

Result:

if (!A)
    return C;
else
    return B;
If Not A Then
    Return C
Else
    Return B
End If

Screenshot

ReverseConditional