Home > Refactorings > Refactorings – Flatten Conditional

Refactorings – Flatten Conditional

March 22nd, 2011

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:

Refactor! Flatten Conditional and Replace Conditional with Guard Clause - before

Result:

Refactor! Flatten Conditional and Replace Conditional with Guard Clause - result

  • Remove Redundant Conditional

Replaces conditional with a single statement, for example:

Before refactoring:

Refactor! Flatten Conditional and Remove Redundant Conditional - before

Result:

Refactor! Flatten Conditional and Remove Redundant Conditional - result

This part of the refactoring can also simplify ternary expressions:

Before refactoring:

Refactor! Flatten Conditional and Remove Redundant Conditional - before

Result:

Refactor! Flatten Conditional and Remove Redundant Conditional on ternary - 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:

Refactor! Flatten Conditional, Remove Conditional and Redundant Redundant Else - before

Result:

Refactor! Flatten Conditional, Remove Conditional and Redundant Redundant Else - result

  • Remove Redundant Else

Removes the ‘else’ block delimiters and unindents it, for example:

Before refactoring:

Refactor! Flatten Conditional and Redundant Redundant Else - before

Result:

Refactor! Flatten Conditional and Redundant Redundant Else - 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: R022

Similar Posts: