Flatten Conditional
- 2 minutes to read
In This Article
Unindents the if or else statement for a conditional. This will apply one of the following refactorings: Replace Nested Conditional with Guard Clause, Remove Redundant Conditional, or Reverse Conditional followed by Remove Redundant Conditional. Flatten Conditional is also smart enough to recognize if (E) returns true; otherwise returns false;
and convert that to return E;
.
#Purpose
This refactoring helps you simplify your conditional clauses, and thus increase code readability.
#Availability
Available from the context menu or via shortcuts:
- Replace Nested Conditional with Guard Clause is available if there’s an if statement that lasts until the end of the method body. If applied, this refactoring reverses the condition and exits the method if it’s true. As the result, the entire body of the previous if clause is unindented.
#Example
public int GetValueA(bool a, bool b)
{ │if (a)
if (!b)
return CalculateValue();
return 0;
}
// Result
public int GetValueA(bool a, bool b) {
if (!a)
return 0;
if (!b)
return CalculateValue();
return 0;
}
Public Function GetValueA(ByVal a As Boolean, ByVal b As Boolean) As Integer│If a Then
If Not b Then
Return CalculateValue()
End If
End If
Return 0
End Function
' Result
Public Function GetValueA(ByVal a As Boolean, ByVal b As Boolean) As Integer
If Not a Then
Return 0
End If
If Not b Then
Return CalculateValue()
End If
Return 0
End Function
#Screenshot
Remove Redundant Conditional unindents an else block if the corresponding if block has a guaranteed return statement at the end.
#Example
if (productAExists)
CalculateTotalA();
│else
CalculateTotalB();
// Result
if (productAExists) {
CalculateTotalA();
return;
}
CalculateTotalB();
If ProductAExists Then
CalculateTotalA()
│Else
CalculateTotalB()
End If
'Result
If ProductAExists Then
CalculateTotalA()
Return
End If
CalculateTotalB()
#Screenshot
See Also