Refactorings – Flatten Conditional
This is one of the most powerful refactorings for conditionals – it helps you to simplify conditional statements by unindenting all or a portion of the conditional statement which improves the clarity of the code. This refactoring includes several different refactorings mentioned in Martin Fowler‘s book, and a few others. These refactorings are applied, depending on the conditional blocks you have inside the source code. Here they are:
- Replace Nested Conditional with Guard Clauses
Replaces nested conditional with a guard clause, inverting the if-clause expression and exiting the code block if the new expression is satisfied. When the conditional behavior does not make the normal path of execution clear, you can remove nested if conditions with a series of separate if statements, for example:
Before refactoring:
Result:
- Remove Redundant Conditional
Replaces conditional with a single statement, for example:
Before refactoring:
Result:
This part of the refactoring can also simplify ternary expressions:
Before refactoring:
Result:
As usual, you can see the preview hint, showing you the resulting code before applying the refactoring:
- Reverse Conditional followed by Remove Redundant Conditional
Inverts the logic of the conditional statement and unindents the redundant ‘else’ block, for example:
Before refactoring:
Result:
- Remove Redundant Else
Removes the ‘else’ block delimiters and unindents it, for example:
Before refactoring:
Result:
All of these refactorings are performed by Flatten Conditional. The refactoring fixes the following code issues:
—– Products: Refactor! Pro, CodeRush Xpress, Refactor! for ASP.NET Versions: 10.2 and up VS IDEs: any Updated: Mar/23/2011 ID: R022Similar Posts:
- Refactoring multi-conditional statements: the switch statement and the “if-else-if” ladder
- Adding and removing block delimiters in C#/C++ and JavaScript
- Refactorings for Loops and Blocks overview
- Differences between paid (Pro) and free Refactor! versions
- Refactoring using statements with CodeRush/Refactor!