Lift Statement Out Of If-Else

Move a duplicated statement to the front or back of an if-else statement.

refactoring
P42
P42+

Why is this useful?

Lifting 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 first or 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. If the if-else does not contain any other statements, it can be removed.

Code Action Safety

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

  1. When lifting out a first statement that impacts the evaluation of the if-condition, the if-else might behave differently after the refactoring. For example,
    let a = 2;
    if (a === 2) {
        a = 3;
        console.log("if");
    } else {
        a = 3;
        console.log("else");
    }
    
    prints "if" before the refactoring and "else" afterward.
  2. When lifting out a first statement, when the if-condition has side-effects, the statement might behave differently than before. For example,

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

    prints "before" before the refactoring and "after" afterward.

  3. 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.

Learn More

Available In