# Collapse If Statements

# Description

Collapses, when possible, the nested if-statements into a single one by concatenating their conditions with the infix operator &&. If the concatenation results to an infix expression with more than two components, then a new local variable is introduced to store the condition.

# Benefits

Improves the readability by reducing the number of the nested language constructs.

# Tags

# Code Changes

# Simple collapse

Pre

    if (a) {
        if (b) {
            System.out.println("Ok");
        }
    }

Post

    if (a && b) {
        System.out.println("Ok");
    }

# Collapsing more than two statements

Pre

    if (a) {
        if (b) {
            if (c) {					
                System.out.println("Ok");
            }
        }
    }

Post

    boolean condition = a && b && c;
    if (condition) {
        System.out.println("Ok");
    }

# Compound conditions

Pre

    if (a) {
        if (b || c) {					
            System.out.println("Ok");
        }
    }

Post

    boolean condition = a && (b || c);
    if (condition) {
        System.out.println("Ok");
    }

🛠️ Auto-refactor Available

You can auto-refactor this with jSparrow.
Drop this button to your Eclipse IDE workspace to install jSparrow for free:

Drag to your running Eclipse* workspace. *Requires Eclipse Marketplace Client

Need help? Check out our installation guide.

# Properties

Property Value
Rule ID CollapseIfStatements
First seen in jSparrow version 3.2.0
Minimum Java version 1.1
Remediation cost 5 min
Links