Collapse If Statements

Properties

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

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.

Requirement & Tags

Requirements

None

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");
    }