Skip to content

[java] CognitiveComplexity does not count switch expressions #6881

Closed

Description

@KurathSec

Affects PMD Version: 7.26.0 (latest release; the same code is on the current main branch, see Root cause below)

Rule: CognitiveComplexity

https://docs.pmd-code.org/latest/pmd_rules_java_design.html#cognitivecomplexity

Description:

CognitiveComplexity adds a structural increment for a switch statement but not for a switch expression (Java 14+). So a switch expression adds nothing to the score. The visitor also does not open a nesting level for it, so anything nested inside a switch expression loses its nesting increment too. Either way the score comes out too low, and the rule misses violations it should report.

The Cognitive Complexity spec gives a switch a single structural increment, no matter how many cases it has (G. Ann Campbell, SonarSource, https://www.sonarsource.com/resources/cognitive-complexity/). A switch expression is the same branching construct as a switch statement, and PMD already scores the two the same way for Cyclomatic Complexity.

Several other rules had the same gap, handling the switch statement but not the switch expression, and were fixed: #5250, #5257, #3362, and the NPathComplexity metric in #2625.

Code Sample demonstrating the issue:

public class SwitchCognitive {

    // switch STATEMENT: reported as cognitive complexity 1 (correct).
    int asStatement(int x) {
        switch (x) {
            case 1: return 10;
            case 2: return 20;
            default: return 0;
        }
    }

    // Same control flow as a switch EXPRESSION: should also be 1,
    // but no violation is reported (cognitive complexity 0).
    int asExpression(int x) {
        return switch (x) {
            case 1 -> 10;
            case 2 -> 20;
            default -> 0;
        };
    }

    // if nested in a switch STATEMENT: reported as 3
    // (switch +1; if +1, plus +1 for nesting inside the switch).
    int nestedInStatement(int x) {
        switch (x) {
            case 1:
                if (x > 0) { return 10; }
                return -10;
            default:
                return 0;
        }
    }

    // The same if nested in a switch EXPRESSION: should also be 3,
    // but is reported as 1. The switch's own +1 is lost, and the
    // inner if loses its nesting increment.
    int nestedInExpression(int x) {
        return switch (x) {
            case 1 -> {
                if (x > 0) { yield 10; }
                yield -10;
            }
            default -> 0;
        };
    }
}

Ruleset used (CognitiveComplexity at the reporting floor so small values are visible; reportLevel cannot be lower than 1, see #5917):

<?xml version="1.0"?>
<ruleset name="cognitive-only" xmlns="http://pmd.sourceforge.net/ruleset/2.0.0">
  <rule ref="category/java/design.xml/CognitiveComplexity">
    <properties>
      <property name="reportLevel" value="1"/>
    </properties>
  </rule>
</ruleset>

Expected outcome:

asExpression should report a cognitive complexity of 1 (equal to asStatement), and nestedInExpression should report 3 (equal to nestedInStatement).

Actual outcome:

The two switch-expression methods score too low. asExpression produces no violation at all (complexity 0, so it is absent below), and nestedInExpression is reported as 1 instead of 3:

SwitchCognitive.java:4:  CognitiveComplexity: The method 'asStatement(int)' has a cognitive complexity of 1, current threshold is 1
SwitchCognitive.java:24: CognitiveComplexity: The method 'nestedInStatement(int)' has a cognitive complexity of 3, current threshold is 1
SwitchCognitive.java:37: CognitiveComplexity: The method 'nestedInExpression(int)' has a cognitive complexity of 1, current threshold is 1

Root cause:

CognitiveComplexityVisitor overrides visit(ASTSwitchStatement, ...) but has no visit(ASTSwitchExpression, ...) and does not import ASTSwitchExpression, so switch expressions are skipped:

https://github.com/pmd/pmd/blob/pmd_releases/7.26.0/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/metrics/internal/CognitiveComplexityVisitor.java#L263

The sibling CycloVisitor in the same package handles both forms by visiting the common supertype ASTSwitchLike:

https://github.com/pmd/pmd/blob/pmd_releases/7.26.0/pmd-java/src/main/java/net/sourceforge/pmd/lang/java/metrics/internal/CycloVisitor.java#L59-L91

Aligning CognitiveComplexityVisitor with CycloVisitor (handle ASTSwitchLike, or add a visit(ASTSwitchExpression, ...) that applies the same structural increment and opens a nesting level) would fix both the missing increment and the lost nesting level.

Running PMD through: CLI

pmd check -R cognitive-only.xml -d SwitchCognitive.java -f text

Environment: PMD 7.26.0, OpenJDK 25, Linux.

Activity

  1. added this to the 7.27.0 milestone on Jul 25, 2026
  2. added a commit that references this issue on Jul 25, 2026
    866fc5a
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions