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.

Refactoring (Move)
P42 for VS Code
P42 for GitHub
Move duplicated last statement out of if-else

Why is this useful?

Moving duplicated statements out of an if-else removes code duplication and clarifies that their execution is not dependent on the condition of the if statement.

Mechanics

If the last statement is the same in the if-block and the else-block of an if-statement, then the statement can be pulled out. and moved below the if-statement. If the if-else does not contain any other statements, it can be removed.

What do I need to consider?

There are some scenarios in which lifting out a duplicated statement can lead to a change of behavior:

  1. When removing an if-else statement with side-effects in the if-condition, the side-effects are no longer executed. For example,

    let a = "before";
    
    const f = () => {
     console.log(a);
     return true;
    };
    
    if (f()) {
     a = "after";
    } else {
     a = "after";
    }

    prints "before" before the refactoring and nothing afterward.

P42 provides safety information when any one of the scenarios is possible.

Configuration

Related Code Assists

Learn More

Available In