switch statement with no when else branch

ID

apex.maintainability.switch_when_else

Severity

high

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Control Flow

Language

Apex

Description

Reports a switch on statement that declares no when else branch.

Rationale

A switch on without a when else does nothing at all for a value none of its branches names. In an org that value arrives on its own schedule: an admin adds a picklist entry, a new record type is deployed, a related record comes back null from the query. The statement then falls straight through, the variable keeps its previous content, and the record is saved or the response returned as though the case had been handled. Because switch on is usually written over exactly the values that existed on the day it was written, it is the construct most likely to be out of date with the org’s configuration.

The following code illustrates the pattern detected by this rule:

public class OrderStatusRouter {

    public static String queueFor(String status) {
        String queue = 'none';
        // FLAGGED: switch statement with no when else branch
        switch on status {
            when 'Draft' {
                queue = 'review';
            }
            when 'Activated' {
                queue = 'fulfilment';
            }
        }
        return queue;
    }

    public static Decimal surchargeFor(String shipping) {
        Decimal surcharge = 0;
        // FLAGGED: switch statement with no when else branch
        switch on shipping {
            when 'Express' {
                surcharge = 9.95;
            }
        }
        return surcharge;
    }

    public static String queueForComplete(String status) {
        String queue;
        switch on status {
            when 'Draft' {
                queue = 'review';
            }
            when 'Activated' {
                queue = 'fulfilment';
            }
            when else {
                queue = 'none';
            }
        }
        return queue;
    }

    public static Decimal surchargeForComplete(String shipping) {
        Decimal surcharge;
        switch on shipping {
            when 'Express' {
                surcharge = 9.95;
            }
            when else {
                surcharge = 0;
            }
        }
        return surcharge;
    }
}

Remediation

Add a when else branch that states what happens for everything not named - a default value, an addError on the record, or a thrown exception carrying the unexpected value so the log says which one it was. A when null branch is worth adding alongside it where the expression can be null, since when else also catches null.

Configuration

This detector does not need any configuration.

© 2026 Xygeni. All rights reserved