pmd / pmd

An extensible multilanguage static code analyzer.
https://pmd.github.io
Other
4.87k stars 1.5k forks source link

[apex] switch statements do not contribute to Cyclomatic Complexity numbers #4863

Open aidan-harding opened 7 months ago

aidan-harding commented 7 months ago

I'm happy to fork the repo and have a go at fixing this if you're happy to accept the changes once you're happy with them.

Affects PMD Version: 6.55

Rule:

Cyclomatic Complexity

Description:

The cyclomatic complexity of a method should be increased by adding a switch statement, but it does not.

Moreover, the documentation states that it covers:

As such, they include all control flow statements, such as ‘if’, ‘while’, ‘for’, and ‘case’.

Which is not only not true, but also syntactically incorrect, as in Apex the keyword when is used instead of case.

Code Sample demonstrating the issue:

public class CyclomaticComplexity {
    void foo() {
        switch on Trigger.operationType {
            when BEFORE_INSERT {
                System.debug('Before Insert');
            }
            when AFTER_INSERT {
                System.debug('After Insert');
            }
        }
    }
}

Expected outcome:

PMD should report a cyclomatic complexity of 3 (starts at one, then +1 for each branch in the switch). It actually reports a cyclomatic complexity of 1.

Running PMD through: CLI

aidan-harding commented 7 months ago

I checked this in 7.0.0-rc4 and it has the same behaviour.