### Run PMD Analysis (Linux/macOS) Source: https://docs.pmd-code.org/latest/pmd_userdocs_installation.html Example of running a PMD analysis on Java sources using the text format and a quickstart ruleset. ```shell ~ $ pmd check -f text -R rulesets/java/quickstart.xml src/main/java .../src/main/java/com/me/RuleSet.java:123 These nested if statements could be combined .../src/main/java/com/me/RuleSet.java:231 Useless parentheses. .../src/main/java/com/me/RuleSet.java:232 Useless parentheses. .../src/main/java/com/me/RuleSet.java:357 These nested if statements could be combined .../src/main/java/com/me/RuleSetWriter.java:66 Avoid empty catch blocks ``` -------------------------------- ### Install All Contributors CLI Source: https://docs.pmd-code.org/latest/pmd_devdocs_contributing.html Install the All Contributors CLI tool in the PMD top-level directory. ```bash npm i ``` -------------------------------- ### Run PMD Analysis (Windows) Source: https://docs.pmd-code.org/latest/pmd_userdocs_installation.html Example of running a PMD analysis on Java sources using the text format and a quickstart ruleset on Windows. ```batch C:\> pmd.bat check -f text -R rulesets/java/quickstart.xml ..\..\src\main\java ...\src\main\java\com\me\RuleSet.java:123 These nested if statements could be combined ...\src\main\java\com\me\RuleSet.java:231 Useless parentheses. ...\src\main\java\com\me\RuleSet.java:232 Useless parentheses. ...\src\main\java\com\me\RuleSet.java:357 These nested if statements could be combined ...\src\main\java\com\me\RuleSetWriter.java:66 Avoid empty catch blocks ``` -------------------------------- ### ApexDoc Example Source: https://docs.pmd-code.org/latest/pmd_rules_apex_documentation.html This example demonstrates a class and method with valid ApexDoc comments. It includes a main description and an @return tag for a non-void method. ```apex /** * Hello World */ public class HelloWorld { /** * Bar * @return Bar */ public Object bar() { return null; } } ``` -------------------------------- ### Install Bundles and Render Release Notes Source: https://docs.pmd-code.org/latest/pmd_projectdocs_committers_releasing.html Installs necessary Ruby gems for rendering release notes and then generates the release notes content. Ensure you are in the 'docs' directory before running. ```bash cd docs bundle config set --local path vendor/bundle bundle install NEW_RELEASE_NOTES=$(bundle exec render_release_notes.rb pages/release_notes.md | tail -n +6) cd .. ``` -------------------------------- ### Build Documentation with Bundler Source: https://docs.pmd-code.org/latest/pmd_devdocs_writing_documentation.html Commands to install dependencies, build the documentation, and serve it locally using Bundler. ```bash # this is required only once, to download and install the dependencies bundle install # this builds the documentation under _site bundle exec jekyll build # this runs a local webserver as http://localhost:4005 bundle exec jekyll serve ``` -------------------------------- ### Install pmdtester Gem Source: https://docs.pmd-code.org/latest/pmd_devdocs_pmdtester.html Installs the pmdtester gem, including pre-release versions. Ensure you have RubyGems installed. ```bash gem install pmdtester --pre ``` -------------------------------- ### Apex NcssConstructorCount Example Source: https://docs.pmd-code.org/latest/pmd_rules_apex_design.html An example constructor demonstrating the NCSS (Non-Commenting Source Statements) line count for the NcssConstructorCount rule. ```apex public class Foo extends Bar { //this constructor only has 1 NCSS lines public Foo() { super(); super.foo(); } } ``` -------------------------------- ### PMD Rule Reference Example Source: https://docs.pmd-code.org/latest/pmd_rules_jsp_bestpractices.html Shows how to reference a PMD rule in a configuration file. This is a common pattern for enabling specific rules. ```xml ``` ```xml ``` ```xml ``` ```xml ``` -------------------------------- ### Configure GuardLogStatement Rule Source: https://docs.pmd-code.org/latest/pmd_rules_java_bestpractices.html Example of how to reference the GuardLogStatement rule with default properties. ```xml ``` -------------------------------- ### Launch PMD Rule Designer on Linux/macOS Source: https://docs.pmd-code.org/latest/pmd_userdocs_extending_your_first_rule.html Use this command to start the PMD Rule Designer on Linux or macOS systems. ```bash ~ $ pmd designer ``` -------------------------------- ### Configure AvoidBranchingStatementAsLastInLoop Rule (XML) Source: https://docs.pmd-code.org/latest/pmd_rules_java_errorprone.html This example shows how to reference the rule with default properties and how to customize it by specifying properties for loop types. ```xml ``` ```xml ``` -------------------------------- ### Configure Apex Formal Parameter Naming Conventions Source: https://docs.pmd-code.org/latest/pmd_rules_apex_codestyle.html Example of how to reference the FormalParameterNamingConventions rule with default properties. ```xml ``` -------------------------------- ### Apex StdCyclomaticComplexity Rule Example Source: https://docs.pmd-code.org/latest/pmd_rules_apex_design.html This example demonstrates a method with high cyclomatic complexity due to multiple decision points like if, else if, while, for, and switch cases. Use this rule to identify overly complex methods. ```apex // 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; } } } ``` -------------------------------- ### Java AST Node Structure Example Source: https://docs.pmd-code.org/latest/pmd_userdocs_extending_writing_rules_intro.html Illustrates the AST structure for a simple Java class declaration. ```text class Foo extends Object { } ``` ```text | ``` └─ CompilationUnit └─ TypeDeclaration └─ ClassDeclaration "Foo" ├─ ModifierList ├─ ExtendsList │ └─ ClassType "Object" └─ ClassBody ``` -------------------------------- ### Example Usage of pmd:startLine() Source: https://docs.pmd-code.org/latest/pmd_userdocs_extending_writing_xpath_rules.html This XPath expression selects `` nodes that start after the fifth line of the source file. It showcases the pmd:startLine() function to retrieve the starting line number of a node. ```xpath //b[pmd:startLine(.) > 5] ``` -------------------------------- ### Initial PMD Build with Maven Source: https://docs.pmd-code.org/latest/pmd_devdocs_building_general.html Perform an initial build of PMD using Maven to set up the environment and aid Maven IDE integration. This step downloads all dependencies and may take time. ```bash cd pmd ./mvnw clean verify -DskipTests ``` -------------------------------- ### Apex ExcessiveParameterList Example Source: https://docs.pmd-code.org/latest/pmd_rules_apex_design.html Demonstrates methods with too many parameters and a preferred approach using objects to group parameters. ```apex 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) { // ... } ``` -------------------------------- ### Get start column of a node Source: https://docs.pmd-code.org/latest/pmd_userdocs_extending_writing_xpath_rules.html Use pmd:startColumn to find the column number where a node begins in the source file. Column numbers are 1-based and inclusive. ```xpath //b[pmd:startColumn(.) = 1] ``` -------------------------------- ### Example sfdx-project.json Configuration Source: https://docs.pmd-code.org/latest/pmd_rules_apex_design.html This configuration includes necessary settings for Apex development, such as package directories, namespace, and external package dependencies, which are important for accurate static analysis. ```json { "packageDirectories": [ { "path": "src", "default": true } ], "namespace": "my_namespace", "sfdcLoginUrl": "https://login.salesforce.com", "sourceApiVersion": "52.0", "plugins": { "dependencies": [ {"namespace": "aa"} ] } } ``` -------------------------------- ### Build Documentation with Docker Source: https://docs.pmd-code.org/latest/pmd_devdocs_writing_documentation.html Commands to build a Docker image for PMD documentation and to build or serve the documentation using the Docker image. ```bash # this is required only once to create a local docker image named "pmd-doc" docker build --no-cache -t pmd-doc . # this builds the documentation under _site docker run --rm=true -v "$PWD:/src" pmd-doc build -H 0.0.0.0 # this runs a local webserver as http://localhost:4005 docker run --rm=true -v "$PWD:/src" -p 4005:4005 pmd-doc serve -H 0.0.0.0 ``` -------------------------------- ### Example Abstract Class Source: https://docs.pmd-code.org/latest/pmd_rules_java_design.html An example of an abstract class with fields but no methods, which could be flagged by the AbstractClassWithoutAnyMethod rule. ```java public abstract class Example { String field; int otherField; } ``` -------------------------------- ### Uncommented Empty Constructor Example Source: https://docs.pmd-code.org/latest/pmd_rules_java_documentation.html Example of an empty constructor that should be commented to distinguish it from unintentional empty constructors. ```java public Foo() { // This constructor is intentionally empty. Nothing special is needed here. } ``` -------------------------------- ### Full Ant Build File Example with Auxclasspath Source: https://docs.pmd-code.org/latest/pmd_userdocs_tools_ant.html A complete Ant build file demonstrating the PMD task with auxclasspath configuration. Ensure your project is compiled first. ```xml rulesets/java/quickstart.xml ``` -------------------------------- ### Apex ExcessivePublicCount Example Source: https://docs.pmd-code.org/latest/pmd_rules_apex_design.html An example class with numerous public attributes, methods, and properties, illustrating the ExcessivePublicCount rule. ```apex 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 ...] } ``` -------------------------------- ### Uncommented Empty Method Body Example Source: https://docs.pmd-code.org/latest/pmd_rules_java_documentation.html Example of an empty method body that should be commented to distinguish it from unintentional empty methods. ```java public void doSomething() { } ``` -------------------------------- ### Run Full Project Build Source: https://docs.pmd-code.org/latest/pmd_projectdocs_committers_merging_pull_requests.html Executes a clean build of the project, including all unit tests and checkstyle tests, using the Maven wrapper. The `-Pgenerate-rule-docs` profile ensures documentation checks are performed. ```bash ./mvnw clean verify -Pgenerate-rule-docs ``` -------------------------------- ### Basic CPD Usage Source: https://docs.pmd-code.org/latest/pmd_userdocs_cpd.html Run CPD with minimum token count and source directory. Supports Linux/macOS and Windows. ```bash ~ $ pmd cpd --minimum-tokens 100 --dir src/main/java ``` ```batch C:\> pmd.bat cpd --minimum-tokens 100 --dir src\main\java ``` -------------------------------- ### Detect JUnit setUp() without @Before annotation Source: https://docs.pmd-code.org/latest/pmd_rules_java_bestpractices.html This rule detects methods named 'setUp()' that are not annotated with @Before (JUnit 4), @BeforeEach/@BeforeAll (JUnit 5), or @BeforeMethod/@BeforeClass (TestNG). It assists in migrating from JUnit 3 conventions or enforcing consistent setup method naming. ```java public class MyTest { public void setUp() { bad(); } } public class MyTest2 { @Before public void setUp() { good(); } } ``` -------------------------------- ### XML Report Example Source: https://docs.pmd-code.org/latest/pmd_userdocs_report_formats.html This is an example of a PMD report in XML format. It can be validated against the report_2_0_0.xsd schema. The 'encoding' property defaults to UTF-8. ```xml Logger calls should be surrounded by log level guards. This for loop can be replaced by a foreach loop ``` -------------------------------- ### Build PMD Documentation with Jekyll Source: https://docs.pmd-code.org/latest/pmd_devdocs_building_general.html Build the PMD documentation site using Jekyll. Ensure you have installed the necessary Ruby gems first. ```bash cd docs bundle install # once bundle exec jekyll build ``` -------------------------------- ### Invalid JavaBean Example Source: https://docs.pmd-code.org/latest/pmd_rules_java_design.html This example demonstrates an invalid JavaBean due to a missing setter for the 'label' property and the absence of 'implements Serializable'. ```java package org.example.beans; public class MyBean { // <-- bean is not serializable, missing "implements Serializable" private String label; // <-- missing setter for property "label" public String getLabel() { return label; } } ``` -------------------------------- ### IntelliJ IDEA CLI Command for Single File Source: https://docs.pmd-code.org/latest/pmd_userdocs_report_formats.html Example of how to invoke PMD with the 'ideaj' format for a single file, specifying necessary properties like fileName, sourcePath, and classAndMethodName. ```bash pmd check -d src/Foo.java -R rulesets/java/quickstart.xml -f ideaj -P fileName=src/Foo.java -P sourcePath=/home/pmd/src -P classAndMethodName=Foo ``` -------------------------------- ### Jekyll Frontmatter Example Source: https://docs.pmd-code.org/latest/pmd_devdocs_writing_documentation.html Example of the YAML frontmatter section at the beginning of a Jekyll page, used for metadata like title and permalink. ```yaml --- title: Writing Documentation last_updated: January 2025 (7.10.0) permalink: pmd_devdocs_writing_documentation.html --- Some Text ``` -------------------------------- ### Ant Verbose Output Example Source: https://docs.pmd-code.org/latest/pmd_userdocs_tools_ant.html Example of running the Ant PMD task with the verbose flag (-v) to see detailed output during execution. ```bash [tom@hal bin]$ ant -v pmd Apache Ant version 1.6.2 compiled on July 16 2004 Buildfile: build.xml Detected Java version: 1.4 in: /usr/local/j2sdk1.4.2_03/jre Detected OS: Linux parsing buildfile build.xml with URI = file:/home/tom/data/pmd/pmd/bin/build.xml Project base dir set to: /home/tom/data/pmd/pmd Build sequence for target `pmd' is [pmd] Complete build sequence is [pmd, copy, cppjavacc, cpd, delete, compile, clean, jar, dist, cpdjnlp, jjtree, javadoc, test, tomserver] pmd: [pmd] Using the normal ClassLoader [pmd] Using these rulesets: rulesets/java/quickstart.xml [pmd] Using rule AvoidMessageDigestField [pmd] Using rule AvoidStringBufferField [pmd] Using rule AvoidUsingHardCodedIP [pmd] Using rule CheckResultSet [pmd] Using rule ConstantsInInterface ... [pmd] Processing file /usr/local/java/src/java/lang/ref/Finalizer.java [pmd] Processing file /usr/local/java/src/java/lang/ref/FinalReference.java [pmd] Processing file /usr/local/java/src/java/lang/ref/PhantomReference.java [pmd] Processing file /usr/local/java/src/java/lang/ref/Reference.java [pmd] Processing file /usr/local/java/src/java/lang/ref/ReferenceQueue.java [pmd] Processing file /usr/local/java/src/java/lang/ref/SoftReference.java [pmd] Processing file /usr/local/java/src/java/lang/ref/WeakReference.java [pmd] 0 problems found BUILD SUCCESSFUL Total time: 2 seconds [tom@hal bin]$ ``` -------------------------------- ### Build Module with Snapshot Dependencies Source: https://docs.pmd-code.org/latest/pmd_devdocs_building_general.html Build a specific module while including snapshot dependencies. Use '-am' to also build dependent modules, or '-Pcentral-portal-snapshots' to activate the snapshot repository. ```bash ./mvnw verify -pl pmd-apex -am ``` ```bash ./mvnw verify -pl pmd-apex -Pcentral-portal-snapshots ``` -------------------------------- ### Example of Inefficient Axis Usage Source: https://docs.pmd-code.org/latest/pmd_rules_xsl_performance.html This example demonstrates the use of the 'descendant::' axis within an XSLT variable selection, which is flagged by the AvoidAxisNavigation rule. ```xml ``` -------------------------------- ### PMD Rule Reference Example Source: https://docs.pmd-code.org/latest/pmd_rules_java_errorprone.html Shows how to reference PMD rules within a PMD configuration file. This is a common pattern for enabling specific checks. ```xml ``` ```xml ``` ```xml ``` ```xml ``` -------------------------------- ### Dump Java AST to XML and Query with xmlstarlet Source: https://docs.pmd-code.org/latest/pmd_userdocs_extending_ast_dump.html Demonstrates dumping a Java AST to an XML file using PMD's ast-dump command and then querying specific nodes using xmlstarlet. ```bash $ cat Foo.java public class Foo { int a; } $ pmd ast-dump --format xml --language java --file Foo.java > Foo.xml $ cat Foo.xml $ xmlstarlet select -t -c "//VariableId[@VariableName='a']" Foo.xml ``` -------------------------------- ### Get Explicit Modifiers with pmd-java:explicitModifiers Source: https://docs.pmd-code.org/latest/pmd_userdocs_extending_writing_xpath_rules.html Use `pmd-java:explicitModifiers` to get only the explicit modifiers of a node. The context node must be a `ModifierOwner`. ```xpath //MethodDeclaration[pmd-java:explicitModifiers() = "public"] ``` -------------------------------- ### Export and Verify GPG Public Key Source: https://docs.pmd-code.org/latest/pmd_devdocs_github_actions_workflows.html Export your GPG public key to a file and then use `gpg --show-keys` to verify its details. This is useful for confirming the key was exported correctly and for uploading to various key servers. ```bash gpg --armor --export 2EFA55D0785C31F956F2F87EA0B5CA1A4E086838 > release-signing-key-2EFA55D0785C31F956F2F87EA0B5CA1A4E086838-public.asc gpg --show-keys release-signing-key-2EFA55D0785C31F956F2F87EA0B5CA1A4E086838-public.asc curl 'https://keys.openpgp.org/vks/v1/by-fingerprint/2EFA55D0785C31F956F2F87EA0B5CA1A4E086838' | gpg --show-keys curl 'https://keyserver.ubuntu.com/pks/lookup?search=0x2EFA55D0785C31F956F2F87EA0B5CA1A4E086838&fingerprint=on&exact=on&options=mr&op=get' | gpg --show-keys curl 'http://pgp.mit.edu/pks/lookup?op=get&search=0x2EFA55D0785C31F956F2F87EA0B5CA1A4E086838' | gpg --show-keys ``` -------------------------------- ### PMD CLI Usage Help Source: https://docs.pmd-code.org/latest/pmd_release_notes_pmd7.html Displays the general usage help for the PMD Command Line Interface, including available commands and exit codes. ```bash $ Usage: pmd [-hV] [COMMAND] -h, --help Show this help message and exit. -V, --version Print version information and exit. Commands: check The PMD standard source code analyzer cpd Copy/Paste Detector - find duplicate code designer The PMD visual rule designer cpd-gui GUI for the Copy/Paste Detector Warning: May not support the full CPD feature set ast-dump Experimental: dumps the AST of parsing source code Exit Codes: 0 Successful analysis, no violations found 1 An unexpected error occurred during execution 2 Usage error, please refer to the command help 4 Successful analysis, at least 1 violation found ``` -------------------------------- ### PLSQL Excessive Object Length Example Source: https://docs.pmd-code.org/latest/pmd_rules_plsql_design.html Example of a PL/SQL package body that might trigger the ExcessiveObjectLength rule. This rule is deprecated and replaced by NcssCount. ```plsql CREATE OR REPLACE PACKAGE BODY Foo AS PROCEDURE bar1 IS BEGIN -- 1000 lines of code END bar1; PROCEDURE bar2 IS BEGIN -- 1000 lines of code END bar2; PROCEDURE bar3 IS BEGIN -- 1000 lines of code END bar3; PROCEDURE barN IS BEGIN -- 1000 lines of code END barn; END; ``` -------------------------------- ### LogicInversion Rule Example Source: https://docs.pmd-code.org/latest/pmd_rules_java_design.html Demonstrates the LogicInversion rule, showing how to use opposite operators instead of negating expressions. Use '!=' instead of '!(==)' and '>=' instead of '!(<)'. ```java public boolean bar(int a, int b) { if (!(a == b)) { // use != return false; } if (!(a < b)) { // use >= return false; } return true; } ``` -------------------------------- ### XPath Rule Deprecation Warning Example Source: https://docs.pmd-code.org/latest/pmd_userdocs_migrating_to_pmd7.html Example of a deprecation warning for an XPath attribute in a custom rule. It suggests using '@Name' instead of '@Image' for 'VariableId'. ```text WARNING: Use of deprecated attribute 'VariableId/@Image' by XPath rule 'VariableNaming' (in ruleset 'VariableNamingRule'), please use @Name instead ``` -------------------------------- ### PLSQL NcssMethodCount Example Source: https://docs.pmd-code.org/latest/pmd_rules_plsql_design.html Example of a PLSQL function to be analyzed by the deprecated NcssMethodCount rule. This rule counts Non-Commenting Source Statements (NCSS) within a method. ```plsql CREATE OR REPLACE PACKAGE BODY AS FUNCTION method RETURN INTEGER IS BEGIN RETURN 1; END; END; ``` -------------------------------- ### PLSQL Excessive Method Length Example Source: https://docs.pmd-code.org/latest/pmd_rules_plsql_design.html Example of a PL/SQL procedure that might trigger the ExcessiveMethodLength rule due to its length. This rule is deprecated and replaced by NcssCount. ```plsql CREATE OR REPLACE PROCEDURE doSomething BEGIN DBMS_OUTPUT.PUT_LINE("Hello world!"); DBMS_OUTPUT.PUT_LINE("Hello world!"); -- 98 copies omitted for brevity. END; ``` -------------------------------- ### Apex TooManyFields Rule Example (Problematic) Source: https://docs.pmd-code.org/latest/pmd_rules_apex_design.html This example shows a class with too many individual fields, which can make it unwieldy. Consider grouping related fields into objects. ```apex public class Person { // too many separate fields Integer birthYear; Integer birthMonth; Integer birthDate; Double height; Double weight; } ``` -------------------------------- ### Control Statement Braces Examples Source: https://docs.pmd-code.org/latest/pmd_rules_java_codestyle.html Illustrates the difference between recommended and not-recommended brace usage in while loops. The preferred approach uses braces for clarity and maintainability. ```java while (true) // not recommended x++; while (true) { // preferred approach x++; } ``` -------------------------------- ### Correct JSP Encoding Example Source: https://docs.pmd-code.org/latest/pmd_rules_jsp_errorprone.html Examples of correctly declared content types with UTF-8 encoding in JSP pages using both meta tags and page directives. ```jsp <%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> ``` ```html ``` -------------------------------- ### IntelliJ IDEA Report Format Example Source: https://docs.pmd-code.org/latest/pmd_userdocs_report_formats.html Formats output for IntelliJ IDEA's external tool integration. It displays violation descriptions and their location within the code, including class and method names. ```text Logger calls should be surrounded by log level guards. at Foo(:124) This for loop can be replaced by a foreach loop at Foo(:58) ``` -------------------------------- ### Reference PMD InstantiationToGetClass Rule Source: https://docs.pmd-code.org/latest/pmd_rules_java_errorprone.html Demonstrates how to reference the `InstantiationToGetClass` rule in PMD using an XML configuration. ```xml ``` -------------------------------- ### Apex Excessive Class Length Example Source: https://docs.pmd-code.org/latest/pmd_rules_apex_design.html An example of an Apex class with multiple methods, each containing a large number of lines, which would be flagged by the ExcessiveClassLength rule. ```apex 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 } } ``` -------------------------------- ### UseUtilityClass Example Source: https://docs.pmd-code.org/latest/pmd_rules_java_design.html This example shows a class with only static methods. The UseUtilityClass rule suggests making such classes utility classes by adding a private constructor to prevent instantiation. ```java public class MaybeAUtility { public static void foo() {} public static void bar() {} } ``` -------------------------------- ### Code Sample with Syntax Highlighting Source: https://docs.pmd-code.org/latest/pmd_devdocs_writing_documentation.html Embed code samples using fenced code blocks with the language specified for syntax highlighting. This example uses Java. ```java public class Foo { public void bar() { System.out.println("x"); } } ``` -------------------------------- ### PLSQL NcssObjectCount Example Source: https://docs.pmd-code.org/latest/pmd_rules_plsql_design.html Example of a PLSQL package to be analyzed by the deprecated NcssObjectCount rule. This rule counts Non-Commenting Source Statements (NCSS) within an Oracle object. ```plsql CREATE OR REPLACE PACKAGE pkg_ IS PROCEDURE Foo IS BEGIN --this class only has 6 NCSS lines super(); super(); END Foo; END; ``` -------------------------------- ### Apex TooManyFields Rule Example (Improved) Source: https://docs.pmd-code.org/latest/pmd_rules_apex_design.html This improved example demonstrates how to manage fields more effectively by grouping related data into dedicated objects, making the class more manageable. ```apex public class Person { // this is more manageable Date birthDate; BodyMeasurements measurements; } ``` -------------------------------- ### Example of Lambda to Method Reference Conversion Source: https://docs.pmd-code.org/latest/pmd_rules_java_codestyle.html Demonstrates how lambdas like `s -> s.length()` and `(x, y) -> Integer.sum(x, y)` can be converted to method references `String::length` and `Integer::sum` respectively. ```java import java.util.stream.Stream; public class LambdaCanBeMethodReference { static { Stream.of("abc", "d") .mapToInt(s -> s.length()) // could be String::length .reduce((x, y) -> Integer.sum(x, y)) // could be Integer::sum .getAsInt(); } } ``` -------------------------------- ### Configure PMD for TextPad (Directory Analysis) Source: https://docs.pmd-code.org/latest/pmd_userdocs_tools_ide_plugins.html This configuration sets up PMD to analyze a directory of Java files within TextPad. Ensure your PMD and JDK paths are correctly specified. The parameters define the PMD execution, output rendering, and ruleset to use. ```text -classpath D:\java\pmd-bin-\lib\pmd-.jar;D:\java\pmd-bin-\lib\asm-3.2.jar;D:\java\pmd-bin-\lib\jaxen-1.1.1.jar net.sourceforge.pmd.PMD -d $FileDir -f net.sourceforge.pmd.renderers.TextPadRenderer -R E:\directory\my_pmd_ruleset.xml -debug ``` -------------------------------- ### Java Comment Required Rule Example Source: https://docs.pmd-code.org/latest/pmd_rules_java_documentation.html This rule checks for the presence or absence of Javadoc comments on various code elements. The example shows a valid Javadoc structure. ```java /** * * * @author Jon Doe */ ``` -------------------------------- ### IntelliJ IDEA CLI Command for Directory Source: https://docs.pmd-code.org/latest/pmd_userdocs_report_formats.html Example of how to invoke PMD with the 'ideaj' format for a directory, omitting the fileName property and using '.method' for classAndMethodName when processing directories. ```bash pmd check -d src -R rulesets/java/quickstart.xml -f ideaj -P sourcePath=/home/pmd/src -P classAndMethodName=.method ``` -------------------------------- ### Java Varargs Array Creation Example Source: https://docs.pmd-code.org/latest/pmd_rules_java_bestpractices.html This example shows an unnecessary explicit array creation for a varargs parameter in `Arrays.asList`. The commented-out line indicates the preferred, more concise syntax. ```java import java.util.Arrays; class C { static { Arrays.asList(new String[]{"foo", "bar",}); // should be Arrays.asList("foo", "bar"); } } ``` -------------------------------- ### Reference NoPackage Rule Source: https://docs.pmd-code.org/latest/pmd_rules_java_codestyle.html Shows how to reference the NoPackage rule in PMD configuration. ```xml ``` -------------------------------- ### Java Cyclomatic Complexity Example Source: https://docs.pmd-code.org/latest/pmd_rules_java_design.html Illustrates a Java method with high cyclomatic complexity, highlighting decision points that contribute to the complexity score. This example is reported by the CyclomaticComplexity rule. ```java class Foo { void baseCyclo() { // Cyclo = 1 highCyclo(); } void highCyclo() { // Cyclo = 10: reported! int x = 0, y = 2; boolean a = false, b = true; if (a && (y == 1 ? b : true)) { // +3 if (y == x) { // +1 while (true) { // +1 if (x++ < 20) { // +1 break; // +1 } } } else if (y == t && !d) { // +2 x = a ? y : x; // +1 } else { x = 2; } } } } ``` -------------------------------- ### PMD CPD Command Example Source: https://docs.pmd-code.org/latest/pmd_release_notes_pmd7.html Demonstrates how to use the PMD Copy/Paste Detector (CPD) command with a specific option to find duplicate code. ```bash pmd cpd --minimum-tokens 100 src/main/java ``` -------------------------------- ### Boolean Get Method Naming Convention Source: https://docs.pmd-code.org/latest/pmd_rules_java_codestyle.html Ensures methods returning boolean or Boolean results are named as predicates (e.g., 'isReady()', 'hasValues()') instead of using the 'get' prefix. ```java public boolean getFoo(); // bad public Boolean getFoo(); // bad public boolean isFoo(); // ok public Boolean isFoo(); // ok public boolean getFoo(boolean bar); // ok, unless checkParameterizedMethods=true ``` -------------------------------- ### PMD AST Dump Help Command Source: https://docs.pmd-code.org/latest/pmd_userdocs_extending_ast_dump.html Displays the help message for the 'pmd ast-dump' command, outlining available options and their descriptions. Use this to understand the full range of customization for AST dumping. ```bash $ pmd ast-dump --help Usage: pmd ast-dump [-Dhi] [-e=] [-f=] [--file=] [-l=] [-P=]... Dumps the AST of parsing source code -D, -v, --debug, --verbose Debug mode. -e, --encoding= Specifies the character set encoding of the source code files -f, --format= The output format. Valid values: xml, text --file= The file to parse and dump. -h, --help Show this help message and exit. -i, --read-stdin Read source from standard input. -l, --language= The source code language. Valid values: apex, ecmascript, html, java, jsp, kotlin, modelica, plsql, pom, scala, swift, vf, vm, wsdl, xml, xsl -P= Key-value pair defining a property for the report format. Supported values for each report format: xml: singleQuoteAttributes - Use single quotes to delimit attribute values Default: true lineSeparator - Line separator to use. The default is platform-specific. The values 'CR', 'CRLF', 'LF', '\r', '\r\n' and '\n' can be used to represent a carriage return, line feed and their combination more easily. Default: renderProlog - True to output a prolog Default: true renderCommonAttributes - True to render attributes like BeginLine, EndLine, etc. Default: false text: onlyAsciiChars - Use only ASCII characters in the structure Default: false maxLevel - Max level on which to recurse. Negative means unbounded Default: -1 ``` -------------------------------- ### Get Logger Instance with SLF4J Source: https://docs.pmd-code.org/latest/pmd_devdocs_logging.html This is the standard way to get a logger instance in Java using SLF4J. It's typically stored in a static final field named LOG. ```java private static final Logger LOG = LoggerFactory.getLogger(MyClass.class); ``` -------------------------------- ### Java Comment Size Rule Example Source: https://docs.pmd-code.org/latest/pmd_rules_java_documentation.html This rule enforces limits on the number of lines and line length for non-header comments. The example demonstrates a comment exceeding the default line limit. ```java /** * * too many lines! * * * * * * * * * * */ ``` -------------------------------- ### Clean and Update Code Source: https://docs.pmd-code.org/latest/pmd_projectdocs_committers_releasing.html Before starting the release preparations, ensure your local code is up-to-date and clean. This involves cleaning the project with Maven wrapper and pulling the latest changes from the repository. ```bash $ ./mvnw clean $ git pull $ git status ``` -------------------------------- ### Use Rule Reference for DoNotTerminateVM Source: https://docs.pmd-code.org/latest/pmd_rules_java_errorprone.html Shows how to reference the DoNotTerminateVM rule in PMD configuration. ```xml ``` -------------------------------- ### Custom Rule Test Setup in Java Source: https://docs.pmd-code.org/latest/pmd_userdocs_extending_testing.html Extend SimpleAggregatorTst and override setUp to register your custom rules and their corresponding rulesets. This is necessary when developing rules outside the PMD source base. ```java package com.example.pmd.rules; import net.sourceforge.pmd.test.SimpleAggregatorTst; class CustomRuleTest extends SimpleAggregatorTst { @Override protected void setUp() { addRule("com/example/pmd/ruleset.xml", "CustomRule"); } } ``` -------------------------------- ### Generate Release Notes Script Source: https://docs.pmd-code.org/latest/pmd_projectdocs_committers_releasing.html Execute the release-notes-generate.sh script with the last and release versions as parameters to update the release notes. Ensure GITHUB_TOKEN is set if rate limiting occurs. ```bash .ci/tool/release-notes-generate.sh 7.14.0 7.15.0 ``` -------------------------------- ### Example of Confusing Ternary Usage Source: https://docs.pmd-code.org/latest/pmd_rules_java_codestyle.html Demonstrates a common pattern that the ConfusingTernary rule aims to rephrase for better readability. This specific example shows a ternary operator where the condition `x != y` could be inverted for clarity. ```java boolean bar(int x, int y) { return (x != y) ? diff : same; } ```