Combine the conditions of nested if statements

Rust pattern

Redundant layers of nesting add undesirable complexity.


Apply with the Grit CLI
grit apply collapsible_if

Combines nested if

BEFORE
let x = 6;
if x > 3 {
    if x < 10 {
        println!("Hello");
    }
}
AFTER
let x = 6;
if x > 3 && x < 10 {
    println!("Hello");
}

Does not combine if statements with side effects

RUST
let x = 6;
if x > 3 {
    println!("Wow!");
    if x < 10 {
        println!("Hello");
    }
}

Does not combine if statements with following side effects

RUST
let x = 6;
if x > 3 {
    if x < 10 {
        println!("Hello");
    }
    println!("Wow!");
}

Combines nested if in else block

BEFORE
let x = 6;
if x > 7 {
    panic!("Too big!");
} else if x > 3 {
    if x < 10 {
        println!("Hello");
    }
}
AFTER
let x = 6;
if x > 7 {
    panic!("Too big!");
} else if x > 3 && x < 10 {
    println!("Hello");
}