
25 Code Assists for Branching Statements
Branching statements such as if-else and switch are central elements in many programs. Restructuring them can increase the readability of your programs, often in combination with refactoring their conditions:
- Add {…} to if-else and loops
Convert single statements into blocks.
- Convert && to if statement
Convert
condition && aFunction();
and similar expression statements into if statements. - Convert conditional expression to if-else
Convert a conditional expression to an if-else statement.
- Convert if-else into conditional expression
Convert an
if
-else
return or assignment expression into a conditional expression. - Convert if-else to switch
Convert a series of if-else statements with equality comparisons into a switch statement.
- Convert switch to if-else
Change a switch statement into a series of if-else statements
- Inline variable occurrence
Inline the value of a variable into one of its occurrences.
- Introduce early return / continue
Change an if-statement into an early return or continue statement.
- Merge if-statement into preceding if-statement
Merges two if-statements with the same body when possible.
- Merge nested if inside else into else-if
Nested single
if
statements insideelse
blocks can be combined intoelse if
statements. - Merge nested if-statements
Combine two nested
if
statements without additional operations into a singleif
-statement, using&&
to combine the conditions. - Move duplicated first statement out of if-else
Move a first statement that appears in both the if and the else block out of the if-else statement.
- Move if-else-if branches
Move an if-else branch up or down.
- Move duplicated last statement out of if-else
Move a last statement that appears in both the if and the else block out of the if-else statement.
- Move nested if
Push down if statements into nested if statements and pull nested if statements up.
- Move switch case clause
Move a
case
clause in aswitch
statement up or down. - Remove {…} from if-else and loops
Replace single statement blocks with their inner statement.
- Remove empty else block
Remove an empty 'else' block from an 'if' statement.
- Remove empty if block
Remove an empty 'if' block from an 'if' statement. Replaces it with the 'else' block when available.
- Remove redundant else if
Remove redundant else-if conditions and unreachable else statements.
- Remove unnecessary conditional expression
Replace a conditional expression with its condition or its result.
- Remove unnecessary else
Lift the else content of an
if
-else
with a return statement to the outer indentation level. - Separate repeated condition into nested if-else
Separate a repeated sub-condition that is fully covered into a nested if-else.
- Simplify switch statement
Remove an unnecessary switch statement or replace it with its content.
- Split if statement
Split the condition of an if statement on
||
or&&
when possible.