Rules that help you discover design issues.
Table of Contents

AvoidDeeplyNestedIfStmts

Since: PMD 5.5.0

Priority: Medium (3)

Avoid creating deeply nested if-then statements since they are harder to read and error-prone to maintain.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.apex.rule.design.AvoidDeeplyNestedIfStmtsRule

Example(s):

public class Foo {
    public void bar(Integer x, Integer y, Integer z) {
        if (x>y) {
            if (y>z) {
                if (z==x) {
                    // !! too deep
                }
            }
        }
    }
}

This rule has the following properties:

Name Default Value Description
problemDepth 3 The if statement depth reporting threshold

Use this rule with the default properties by just referencing it:

<rule ref="category/apex/design.xml/AvoidDeeplyNestedIfStmts" />

Use this rule and customize it:

<rule ref="category/apex/design.xml/AvoidDeeplyNestedIfStmts">
    <properties>
        <property name="problemDepth" value="3" />
    </properties>
</rule>

CognitiveComplexity

Since: PMD 6.22.0

Priority: Medium (3)

Methods that are highly complex are difficult to read and more costly to maintain. If you include too much decisional logic within a single method, you make its behavior hard to understand and more difficult to modify.

Cognitive complexity is a measure of how difficult it is for humans to read and understand a method. Code that contains a break in the control flow is more complex, whereas the use of language shorthands doesn’t increase the level of complexity. Nested control flows can make a method more difficult to understand, with each additional nesting of the control flow leading to an increase in cognitive complexity.

Information about Cognitive complexity can be found in the original paper here: https://www.sonarsource.com/docs/CognitiveComplexity.pdf

By default, this rule reports methods with a complexity of 15 or more. Reported methods should be broken down into less complex components.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.apex.rule.design.CognitiveComplexityRule

Example(s):

public class Foo {
    // Has a cognitive complexity of 0
    public void createAccount() {
        Account account = new Account(Name = 'PMD');
        insert account;
    }

    // Has a cognitive complexity of 1
    public Boolean setPhoneNumberIfNotExisting(Account a, String phone) {
        if (a.Phone == null) {                          // +1
            a.Phone = phone;
            update a;
            return true;
        }

        return false;
    }

    // Has a cognitive complexity of 4
    public void updateContacts(List<Contact> contacts) {
        List<Contact> contactsToUpdate = new List<Contact>();

        for (Contact contact : contacts) {                           // +1
            if (contact.Department == 'Finance') {                   // +2 (nesting = 1)
                contact.Title = 'Finance Specialist';
                contactsToUpdate.add(contact);
            } else if (contact.Department == 'Sales') {              // +1
                contact.Title = 'Sales Specialist';
                contactsToUpdate.add(contact);
            }
        }

        update contactsToUpdate;
    }
}

This rule has the following properties:

Name Default Value Description
classReportLevel 50 Total class cognitive complexity reporting threshold
methodReportLevel 15 Cognitive complexity reporting threshold

Use this rule with the default properties by just referencing it:

<rule ref="category/apex/design.xml/CognitiveComplexity" />

Use this rule and customize it:

<rule ref="category/apex/design.xml/CognitiveComplexity">
    <properties>
        <property name="classReportLevel" value="50" />
        <property name="methodReportLevel" value="15" />
    </properties>
</rule>

CyclomaticComplexity

Since: PMD 6.0.0

Priority: Medium (3)

The complexity of methods directly affects maintenance costs and readability. Concentrating too much decisional logic in a single method makes its behaviour hard to read and change.

Cyclomatic complexity assesses the complexity of a method by counting the number of decision points in a method, plus one for the method entry. Decision points are places where the control flow jumps to another place in the program. As such, they include all control flow statements, such as ‘if’, ‘while’, ‘for’, and ‘case’.

Generally, numbers ranging from 1-4 denote low complexity, 5-7 denote moderate complexity, 8-10 denote high complexity, and 11+ is very high complexity. By default, this rule reports methods with a complexity >= 10. Additionally, classes with many methods of moderate complexity get reported as well once the total of their methods’ complexities reaches 40, even if none of the methods was directly reported.

Reported methods should be broken down into several smaller methods. Reported classes should probably be broken down into subcomponents.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.apex.rule.design.CyclomaticComplexityRule

Example(s):

public class Complicated {
  public void example() { // This method has a cyclomatic complexity of 12
    int x = 0, y = 1, z = 2, t = 2;
    boolean a = false, b = true, c = false, d = true;
    if (a && b || b && d) {
      if (y == z) {
        x = 2;
      } else if (y == t && !d) {
        x = 2;
      } else {
        x = 2;
      }
    } else if (c && d) {
      while (z < y) {
        x = 2;
      }
    } else {
      for (int n = 0; n < t; n++) {
        x = 2;
      }
    }
  }
}

This rule has the following properties:

Name Default Value Description
classReportLevel 40 Total class complexity reporting threshold
methodReportLevel 10 Cyclomatic complexity reporting threshold

Use this rule with the default properties by just referencing it:

<rule ref="category/apex/design.xml/CyclomaticComplexity" />

Use this rule and customize it:

<rule ref="category/apex/design.xml/CyclomaticComplexity">
    <properties>
        <property name="classReportLevel" value="40" />
        <property name="methodReportLevel" value="10" />
    </properties>
</rule>

ExcessiveClassLength

Since: PMD 5.5.0

Priority: Medium (3)

Excessive class file lengths are usually indications that the class may be burdened with excessive responsibilities that could be provided by external classes or functions. In breaking these methods apart the code becomes more managable and ripe for reuse.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.apex.rule.design.ExcessiveClassLengthRule

Example(s):

public class Foo {
    public void bar1() {
        // 1000 lines of code
    }
    public void bar2() {
        // 1000 lines of code
    }
    public void bar3() {
        // 1000 lines of code
    }
    public void barN() {
        // 1000 lines of code
    }
}

This rule has the following properties:

Name Default Value Description
minimum 1000 Threshold above which a node is reported

Use this rule with the default properties by just referencing it:

<rule ref="category/apex/design.xml/ExcessiveClassLength" />

Use this rule and customize it:

<rule ref="category/apex/design.xml/ExcessiveClassLength">
    <properties>
        <property name="minimum" value="1000" />
    </properties>
</rule>

ExcessiveParameterList

Since: PMD 5.5.0

Priority: Medium (3)

Methods with numerous parameters are a challenge to maintain, especially if most of them share the same datatype. These situations usually denote the need for new objects to wrap the numerous parameters.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.apex.rule.design.ExcessiveParameterListRule

Example(s):

// too many arguments liable to be mixed up
public void addPerson(Integer birthYear, Integer birthMonth, Integer birthDate, Integer height, Integer weight, Integer ssn) {
    // ...
}
// preferred approach
public void addPerson(Date birthdate, BodyMeasurements measurements, int ssn) {
    // ...
}

This rule has the following properties:

Name Default Value Description
minimum 4 Threshold above which a node is reported

Use this rule with the default properties by just referencing it:

<rule ref="category/apex/design.xml/ExcessiveParameterList" />

Use this rule and customize it:

<rule ref="category/apex/design.xml/ExcessiveParameterList">
    <properties>
        <property name="minimum" value="4" />
    </properties>
</rule>

ExcessivePublicCount

Since: PMD 5.5.0

Priority: Medium (3)

Classes with large numbers of public methods, attributes, and properties require disproportionate testing efforts since combinatorial side effects grow rapidly and increase risk. Refactoring these classes into smaller ones not only increases testability and reliability but also allows new variations to be developed easily.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.apex.rule.design.ExcessivePublicCountRule

Example(s):

public class Foo {
    public String value;
    public Bar something;
    public Variable var;
    // [... more more public attributes ...]

    public void doWork() {}
    public void doMoreWork() {}
    public void doWorkAgain() {}
    // [... more more public methods ...]

    public String property1 { get; set; }
    // [... more more public properties ...]
}

This rule has the following properties:

Name Default Value Description
minimum 20 Threshold above which a node is reported

Use this rule with the default properties by just referencing it:

<rule ref="category/apex/design.xml/ExcessivePublicCount" />

Use this rule and customize it:

<rule ref="category/apex/design.xml/ExcessivePublicCount">
    <properties>
        <property name="minimum" value="20" />
    </properties>
</rule>

NcssConstructorCount

Since: PMD 5.5.0

Priority: Medium (3)

This rule uses the NCSS (Non-Commenting Source Statements) algorithm to determine the number of lines of code for a given constructor. NCSS ignores comments, and counts actual statements. Using this algorithm, lines of code that are split are counted as one.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.apex.rule.design.NcssConstructorCountRule

Example(s):

public class Foo extends Bar {
    //this constructor only has 1 NCSS lines
    public Foo() {
        super();




        super.foo();
}
}

This rule has the following properties:

Name Default Value Description
minimum 20 Threshold above which a node is reported

Use this rule with the default properties by just referencing it:

<rule ref="category/apex/design.xml/NcssConstructorCount" />

Use this rule and customize it:

<rule ref="category/apex/design.xml/NcssConstructorCount">
    <properties>
        <property name="minimum" value="20" />
    </properties>
</rule>

NcssMethodCount

Since: PMD 5.5.0

Priority: Medium (3)

This rule uses the NCSS (Non-Commenting Source Statements) algorithm to determine the number of lines of code for a given method. NCSS ignores comments, and counts actual statements. Using this algorithm, lines of code that are split are counted as one.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.apex.rule.design.NcssMethodCountRule

Example(s):

public class Foo extends Bar {
    //this method only has 1 NCSS lines
    public Integer method() {
        super.method();



        return 1;
    }
}

This rule has the following properties:

Name Default Value Description
minimum 40 Threshold above which a node is reported

Use this rule with the default properties by just referencing it:

<rule ref="category/apex/design.xml/NcssMethodCount" />

Use this rule and customize it:

<rule ref="category/apex/design.xml/NcssMethodCount">
    <properties>
        <property name="minimum" value="40" />
    </properties>
</rule>

NcssTypeCount

Since: PMD 5.5.0

Priority: Medium (3)

This rule uses the NCSS (Non-Commenting Source Statements) algorithm to determine the number of lines of code for a given type. NCSS ignores comments, and counts actual statements. Using this algorithm, lines of code that are split are counted as one.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.apex.rule.design.NcssTypeCountRule

Example(s):

//this class only has 6 NCSS lines
public class Foo extends Bar {
    public Foo() {
        super();





        super.foo();
    }
}

This rule has the following properties:

Name Default Value Description
minimum 500 Threshold above which a node is reported

Use this rule with the default properties by just referencing it:

<rule ref="category/apex/design.xml/NcssTypeCount" />

Use this rule and customize it:

<rule ref="category/apex/design.xml/NcssTypeCount">
    <properties>
        <property name="minimum" value="500" />
    </properties>
</rule>

StdCyclomaticComplexity

Since: PMD 5.5.0

Priority: Medium (3)

Complexity directly affects maintenance costs is determined by the number of decision points in a method plus one for the method entry. The decision points include ‘if’, ‘while’, ‘for’, and ‘case labels’ calls. Generally, numbers ranging from 1-4 denote low complexity, 5-7 denote moderate complexity, 8-10 denote high complexity, and 11+ is very high complexity.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.apex.rule.design.StdCyclomaticComplexityRule

Example(s):

// This has a Cyclomatic Complexity = 12
public class Foo {
1   public void example() {
2   if (a == b || (c == d && e == f)) {
3       if (a1 == b1) {
            fiddle();
4       } else if a2 == b2) {
            fiddle();
        }  else {
            fiddle();
        }
5   } else if (c == d) {
6       while (c == d) {
            fiddle();
        }
7   } else if (e == f) {
8       for (int n = 0; n < h; n++) {
            fiddle();
        }
    } else {
        switch (z) {
9           case 1:
                fiddle();
                break;
10          case 2:
                fiddle();
                break;
11          case 3:
                fiddle();
                break;
12          default:
                fiddle();
                break;
        }
    }
}

This rule has the following properties:

Name Default Value Description
reportLevel 10 Cyclomatic Complexity reporting threshold
showClassesComplexity true Add class average violations to the report
showMethodsComplexity true Add method average violations to the report

Use this rule with the default properties by just referencing it:

<rule ref="category/apex/design.xml/StdCyclomaticComplexity" />

Use this rule and customize it:

<rule ref="category/apex/design.xml/StdCyclomaticComplexity">
    <properties>
        <property name="reportLevel" value="10" />
        <property name="showClassesComplexity" value="true" />
        <property name="showMethodsComplexity" value="true" />
    </properties>
</rule>

TooManyFields

Since: PMD 5.5.0

Priority: Medium (3)

Classes that have too many fields can become unwieldy and could be redesigned to have fewer fields, possibly through grouping related fields in new objects. For example, a class with individual city/state/zip fields could park them within a single Address field.

This rule is defined by the following Java class: net.sourceforge.pmd.lang.apex.rule.design.TooManyFieldsRule

Example(s):

public class Person {
    // too many separate fields
    Integer birthYear;
    Integer birthMonth;
    Integer birthDate;
    Double height;
    Double weight;
}

public class Person {
    // this is more manageable
    Date birthDate;
    BodyMeasurements measurements;
}

This rule has the following properties:

Name Default Value Description
maxfields 15 Max allowable fields

Use this rule with the default properties by just referencing it:

<rule ref="category/apex/design.xml/TooManyFields" />

Use this rule and customize it:

<rule ref="category/apex/design.xml/TooManyFields">
    <properties>
        <property name="maxfields" value="15" />
    </properties>
</rule>

UnusedMethod

Since: PMD 7.0.0

Priority: Medium (3)

Avoid having unused methods since they make understanding and maintaining code harder.

This rule finds not only unused private methods, but public methods as well.

ApexLink is used to make this possible and this needs additional configuration. The environment variable PMD_APEX_ROOT_DIRECTORY needs to be set prior to executing PMD. With this variable the root directory of the Salesforce metadata, where sfdx-project.json resides, is specified. ApexLink can then load all the classes in the project and figure out, whether a method is used or not.

For an accurate analysis it is important that the PMD_APEX_ROOT_DIRECTORY contains a complete set of metadata that may be referenced from the Apex source code, such as Custom Objects, Visualforce Pages, Flows and Labels. The PMD_APEX_ROOT_DIRECTORY directory must contain a sfdx-project.json, but metadata may be either in the SFDX Source format or the older MDAPI format. The packageDirectories entries in sfdx-project.json are used to determine which directories to search for metadata, if a .forceignore file is present it will be respected.

If the Apex code references external packages via namespace(s) you should declare these in your sfdx-project.json file using the ‘plugins’ syntax shown in the example below to avoid errors. Here’s an example of a well-formed sfdx-project.json:

{
    "packageDirectories": [
      {
        "path": "src",
        "default": true
      }
    ],
    "namespace": "my_namespace",
    "sfdcLoginUrl": "https://login.salesforce.com",
    "sourceApiVersion": "52.0",
    "plugins": {
        "dependencies": [
            {"namespace": "aa"}
        ]
    }
}

This rule is defined by the following Java class: net.sourceforge.pmd.lang.apex.rule.design.UnusedMethodRule

Example(s):

public class Triangle {
    private Double side1;
    private Double side2;
    private Double side3;

    public Triangle(Double side1, Double side2, Double side3) {
        this.side1 = side1;
        this.side2 = side2;
        this.side3 = side3;
    }

    // Method is not invoked so can be removed
    public Double area() {
        return (side1 + side2 + side3)/2;
    }
}

Use this rule by referencing it:

<rule ref="category/apex/design.xml/UnusedMethod" />