Three levels of nested if statements

ID

apex.maintainability.deeply_nested_if

Severity

high

Remediation Complexity

medium

Remediation Risk

medium

Remediation Effort

medium

Resource

Complexity

Language

Apex

Description

Reports an if statement nested three levels deep, counting only if bodies.

Rationale

At three levels the reader has to hold three live conditions to know why a statement runs, and every later edit has to re-establish them. In Apex this shape concentrates in trigger handlers, where the outer tests are usually context checks (Trigger.isInsert, a record type, a null guard) that could be guard clauses returning early, and the innermost body is the only code that matters. Deep nesting is also where a governor-limit-heavy call hides from review.

The following code illustrates the pattern detected by this rule:

public class NestedIfs {

    public void handle(Account a, Boolean isInsert, Boolean isUpdate) {
        // FLAGGED: Three levels of nested if statements
        if (a != null) {
            if (isInsert) {
                if (a.Name != null) {
                    System.debug('deep');
                }
            }
        }
    }

    public void guarded(Account a, Boolean isInsert) {
        if (a == null) {
            return;
        }
        if (isInsert && a.Name != null) {
            System.debug('flat');
        }
    }

    public void twoLevels(Account a, Boolean isInsert) {
        if (a != null) {
            if (isInsert) {
                System.debug('two');
            }
        }
    }
}

Remediation

Turn the outer conditions into guard clauses that return early, or extract the inner body into a method whose name states the case it handles. Where the tests are independent, combining them with && removes a level without changing behaviour.

Configuration

This detector does not need any configuration.

© 2026 Xygeni. All rights reserved