diff --git a/.github/dependabot.yml b/.github/dependabot.yml
new file mode 100644
index 00000000..845c53e5
--- /dev/null
+++ b/.github/dependabot.yml
@@ -0,0 +1,27 @@
+version: 2
+updates:
+- package-ecosystem: maven
+ directory: "/"
+ schedule:
+ interval: daily
+ time: "04:00"
+ open-pull-requests-limit: 10
+ ignore:
+ - dependency-name: org.sonarsource.parent:parent
+ versions:
+ - "55"
+ - 57.0.19
+ - dependency-name: net.sourceforge.pmd:pmd-java
+ versions:
+ - 6.32.0
+ - 6.33.0
+ - dependency-name: org.sonarsource.java:java-frontend
+ versions:
+ - 6.11.0.24617
+ - 6.14.0.25463
+ - dependency-name: org.sonarsource.orchestrator:sonar-orchestrator
+ versions:
+ - 3.35.0.2707
+ - dependency-name: org.sonarsource.sonarqube:sonar-plugin-api
+ versions:
+ - 8.6.1.40680
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
new file mode 100644
index 00000000..48136fc9
--- /dev/null
+++ b/.github/workflows/build.yml
@@ -0,0 +1,112 @@
+name: Build and test
+
+on:
+ push:
+ paths-ignore:
+ - '.github/**'
+ - '**/*.md'
+ tags-ignore:
+ - '**'
+ branches: [ master ]
+ pull_request:
+ branches: [ master ]
+ workflow_dispatch:
+ inputs:
+ skipTests:
+ description: "Skip unit tests?"
+ required: true
+ default: false
+ type: boolean
+ deploySnapshot:
+ description: "Deploy snapshot to Maven Central?"
+ required: true
+ default: false
+ type: boolean
+ runIntegrationTests:
+ description: "Run integration tests?"
+ required: true
+ default: false
+ type: boolean
+
+defaults:
+ run:
+ shell: bash
+
+jobs:
+ build:
+ runs-on: ubuntu-latest
+ timeout-minutes: 20
+ env:
+ # Respect manual input for skipping unit tests (no effect for push/PR where inputs are empty)
+ SKIP_TESTS: ${{ github.event.inputs.skipTests }}
+ steps:
+ - uses: actions/checkout@v5
+
+ - name: Set Release version env variable
+ run: |
+ echo "TAG_NAME=$(mvn help:evaluate -Dexpression=project.version -q -DforceStdout)" >> $GITHUB_ENV
+
+ - name: Set branch name env variable
+ run: |
+ if [ "${{ github.event_name }}" = "pull_request" ]; then
+ BRANCH_NAME="${{ github.head_ref }}"
+ else
+ BRANCH_NAME="${GITHUB_REF#refs/heads/}"
+ fi
+
+ if [ "$BRANCH_NAME" = "master" ]; then
+ echo "ARTIFACT_SUFFIX=" >> $GITHUB_ENV
+ else
+ # Sanitize branch name by replacing invalid characters with dashes
+ SANITIZED_BRANCH=$(echo "$BRANCH_NAME" | sed 's/[\/\\:*?"<>|]/-/g')
+ echo "ARTIFACT_SUFFIX=-$SANITIZED_BRANCH" >> $GITHUB_ENV
+ fi
+
+ # only build SNAPSHOTS, use release for tagged releases
+ - name: Check if tag contains SNAPSHOT
+ if: contains(env.TAG_NAME, 'SNAPSHOT') != true
+ run: |
+ echo "Tag '$TAG_NAME' does not contain 'SNAPSHOT', failing build."
+ exit 1
+
+ - name: Set up JDK 17
+ uses: actions/setup-java@v5
+ with:
+ distribution: 'zulu'
+ java-version: 17
+ cache: 'maven'
+ server-id: central
+ server-username: MAVEN_USERNAME
+ server-password: MAVEN_PASSWORD
+ gpg-passphrase: MAVEN_GPG_PASSPHRASE
+ gpg-private-key: ${{ secrets.GPG_SIGNING_KEY }}
+
+ - name: Build package with maven
+ run: |
+ ./mvnw --batch-mode $(if [ "$SKIP_TESTS" = "true" ]; then echo "-DskipTests"; fi) clean package
+
+ - name: Run integration tests (manual trigger only)
+ if: github.event_name == 'workflow_dispatch' && github.event.inputs.runIntegrationTests == 'true'
+ run: |
+ ./mvnw --batch-mode -pl integration-test -am clean verify
+
+ - name: Deploy SNAPSHOT to maven central
+ if: (github.event_name == 'push' && github.ref == 'refs/heads/master') || (github.event_name == 'workflow_dispatch' && github.event.inputs.deploySnapshot == 'true')
+ env:
+ MAVEN_USERNAME: ${{ secrets.SONATYPE_USERNAME }}
+ MAVEN_PASSWORD: ${{ secrets.SONATYPE_PASSWORD }}
+ MAVEN_GPG_PASSPHRASE: ${{ secrets.GPG_SIGNING_PASSWORD }}
+ run: |
+ ./mvnw --batch-mode $(if [ "$SKIP_TESTS" = "true" ]; then echo "-DskipTests"; fi) clean deploy
+
+ - name: Upload sonar-pmd-plugin jar
+ uses: actions/upload-artifact@v4
+ with:
+ name: sonar-pmd-plugin-${{ env.TAG_NAME }}${{ env.ARTIFACT_SUFFIX }}
+ path: sonar-pmd-plugin/target/sonar-pmd-plugin-*.jar
+
+ - name: Upload sonar-pmd-lib jar
+ uses: actions/upload-artifact@v4
+ with:
+ name: sonar-pmd-lib-${{ env.TAG_NAME }}${{ env.ARTIFACT_SUFFIX }}
+ path: sonar-pmd-lib/target/sonar-pmd-lib-*.jar
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
new file mode 100644
index 00000000..13cac662
--- /dev/null
+++ b/.github/workflows/release.yml
@@ -0,0 +1,49 @@
+name: Release to Maven Central
+run-name: Build ${{ github.ref_name }} by @${{ github.actor }}
+
+on:
+ release:
+ types: [ published ]
+ workflow_dispatch:
+
+defaults:
+ run:
+ shell: bash
+
+jobs:
+ release:
+ runs-on: ubuntu-latest
+ timeout-minutes: 20
+ steps:
+ - uses: actions/checkout@v5
+
+ - name: Set Release version env variable
+ run: |
+ echo "TAG_NAME=${{ github.event.release.tag_name }}" >> $GITHUB_ENV
+
+ # if no tag exists, this is expected to fail
+ - name: Switch to git tag for release
+ run: |
+ git fetch --all --tags -f
+ git checkout tags/${{ env.TAG_NAME }} -b ${{ env.TAG_NAME }}-tmp-branch
+
+ - name: Set up JDK 17
+ uses: actions/setup-java@v5
+ with:
+ distribution: 'zulu'
+ java-version: 17
+ cache: 'maven'
+ server-id: central
+ server-username: MAVEN_USERNAME
+ server-password: MAVEN_PASSWORD
+ gpg-passphrase: MAVEN_GPG_PASSPHRASE
+ gpg-private-key: ${{ secrets.GPG_SIGNING_KEY }}
+
+ - name: Deploy
+ env:
+ MAVEN_USERNAME: ${{ secrets.SONATYPE_USERNAME }}
+ MAVEN_PASSWORD: ${{ secrets.SONATYPE_PASSWORD }}
+ MAVEN_GPG_PASSPHRASE: ${{ secrets.GPG_SIGNING_PASSWORD }}
+ run: |
+ ./mvnw --batch-mode -Drevision=${{ env.TAG_NAME }} -P release clean deploy
+
diff --git a/.gitignore b/.gitignore
index a95e9ab7..b5dac6a1 100644
--- a/.gitignore
+++ b/.gitignore
@@ -27,3 +27,5 @@ Thumbs.db
# Folder config file
Desktop.ini
.java-version
+
+.flattened-pom.xml
diff --git a/.mvn/maven.config b/.mvn/maven.config
new file mode 100644
index 00000000..438c5313
--- /dev/null
+++ b/.mvn/maven.config
@@ -0,0 +1 @@
+-Drevision=4.2.0-SNAPSHOT
diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties
new file mode 100644
index 00000000..48a56c99
--- /dev/null
+++ b/.mvn/wrapper/maven-wrapper.properties
@@ -0,0 +1,19 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+wrapperVersion=3.3.2
+distributionType=only-script
+distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.6/apache-maven-3.9.6-bin.zip
diff --git a/.travis.yml b/.travis.yml
deleted file mode 100644
index 3e8bed38..00000000
--- a/.travis.yml
+++ /dev/null
@@ -1,34 +0,0 @@
-language: java
-sudo: false
-
-addons:
- sonarcloud:
- organization: "jensgerdes-github"
- token:
- secure: "U299FqcJAMNfblrZF8R/ivqRk7KNdSOdcyWI4h5dgOLlQHj+HHrF2GJB2fOVeaB53snOkCycM/ZQgqTLlS1PU2NUca3TroNXj6jpNK1Erb/TXqFMKK+rmsN+hcxudDYGnQFIVnWy4lsg72jlK3Qvktt0XyfuYjMqQbsp3zwhlxw="
-
-jdk:
-- openjdk11
-
-install: true
-script: ./travis.sh
-env:
-- TEST=ci
-- TEST=plugin SQ_VERSION=LATEST_RELEASE[6.7] SJ_VERSION=LATEST_RELEASE[5.0]
-- TEST=plugin SQ_VERSION=LATEST_RELEASE[7.2] SJ_VERSION=LATEST_RELEASE[5]
-- TEST=plugin SQ_VERSION=LATEST_RELEASE[7.8] SJ_VERSION=LATEST_RELEASE[5]
-- TEST=plugin SQ_VERSION=LATEST_RELEASE[7.9] SJ_VERSION=DEV
-- TEST=plugin SQ_VERSION=LATEST_RELEASE[8.1] SJ_VERSION=DEV
-- TEST=plugin SQ_VERSION=DEV SJ_VERSION=DEV
-- TEST=javadoc
-
-cache:
- directories:
- - '$HOME/.m2/repository'
- - '$HOME/.sonar'
- - '$HOME/jvm'
- - '$HOME/maven'
-
-notifications:
- email:
- - jens@gerdes.digital
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c4c7dd44..e3144614 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,9 +1,159 @@
# Changelog
-## [3.2.2-SNAPSHOT](https://github.com/jensgerdes/sonar-pmd/tree/master) (2019-04-17)
-[Full Changelog](https://github.com/jensgerdes/sonar-pmd/compare/3.2.1...master)
+[//]: # (## [4.3.0-SNAPSHOT](https://github.com/jborgers/sonar-pmd/tree/4.3.0-SNAPSHOT) (2025-xx-xx))
-None, yet.
+[//]: # ()
+[//]: # ([Full Changelog](https://github.com/jborgers/sonar-pmd/compare/4.2.0..master))
+
+[//]: # ()
+[//]: # (**Implemented highlights**)
+
+## [4.2.0](https://github.com/jborgers/sonar-pmd/tree/4.2.0) (2025-10-13)
+
+[Full Changelog](https://github.com/jborgers/sonar-pmd/compare/4.1.0..4.2.0)
+
+**Implemented highlights**
+* Java 25 support
+* Now PMD Java and Kotlin rules are available from 7.17.0 (292, up from 282), see details [pmd_release_notes_4.2.0.md](docs/pmd_release_notes_4.2.0.md)
+* Activate Kotlin sensor
+* Add params in sonar rules xml based on Java Rule properties
+* Fix Analysis scope for main and test sources
+* Adjust severity level for code-style category
+
+## [4.1.0](https://github.com/jborgers/sonar-pmd/tree/4.1.0) (2025-07-18)
+[Full Changelog](https://github.com/jborgers/sonar-pmd/compare/4.0.3..4.1.0)
+
+**Implemented highlights**
+* Now all current PMD Java rules are available (282, up from 206), see details [pmd_release_notes_4.1.0.md](docs/pmd_release_notes_4.1.0.md)
+* Generate Sonar rules xml for the plugin directly from the PMD 7.15.0 rules xml: makes all Java rules available and up-to-date automatically
+* Updated and non-deprecated the "PMD XPath Template Rule" (pmd:XPathRule) to create custom Java rules with powerful PMD7 XPath expressions
+* Generate nicely formatted html descriptions from the PMD rule description markup
+* Added `pmd` tag and category tag for each rule
+* Added `has-sonar-alternative` tag for rules with known Sonar alternative (instead of making rules with alternatives `Deprecated`)
+* Simplified release process by automation
+* Maven release via Sonatype Central Portal
+
+## [4.0.3](https://github.com/jborgers/sonar-pmd/tree/4.0.3) (2025-06-06)
+
+Versions update release.
+
+**Implemented highlights**
+* Include PMD 7.14.0
+* Updated minor dependencies
+* Fix pom.xml revision tags in release
+
+[Full Changelog](https://github.com/jborgers/sonar-pmd/compare/4.0.2..4.0.3)
+
+**Implemented highlights**
+* Remove the custom profile importer/exporter to support SonarQube Server 25.4 [#504](https://github.com/jborgers/sonar-pmd/issues/504)
+* Add unused assignment rule [#505](https://github.com/jborgers/sonar-pmd/pull/505)
+* Include PMD 7.13.0
+
+## [4.0.2](https://github.com/jborgers/sonar-pmd/tree/4.0.2) (2025-06-06)
+
+Bugfix release to work with latest SonarQube releases. See [#508](https://github.com/jborgers/sonar-pmd/issues/508) and [#509](https://github.com/jborgers/sonar-pmd/issues/509).
+
+[Full Changelog](https://github.com/jborgers/sonar-pmd/compare/4.0.1..4.0.2)
+
+**Implemented highlights**
+* Remove the custom profile importer/exporter to support SonarQube Server 25.4 [#504](https://github.com/jborgers/sonar-pmd/issues/504)
+* Add unused assignment rule [#505](https://github.com/jborgers/sonar-pmd/pull/505)
+* Include PMD 7.13.0
+
+## [4.0.1](https://github.com/jborgers/sonar-pmd/tree/4.0.1) (2025-03-03)
+[Full Changelog](https://github.com/jborgers/sonar-pmd/compare/4.0.0..4.0.1)
+
+**Implemented highlights**
+* Fix supported java versions from 21 up to 24-preview [#499](https://github.com/jborgers/sonar-pmd/pull/499)
+* Removed all junit tests, they have been moved or removed in PMD7 [#502](https://github.com/jborgers/sonar-pmd/pull/502)
+
+**Limitations**
+* Not all PMD 7 rules are made available in Sonar, yet, see [#495](https://github.com/jborgers/sonar-pmd/issues/495), [#498](https://github.com/jborgers/sonar-pmd/issues/498)
+
+**Contributors**
+* [Markus](https://github.com/meisenla)
+
+## [4.0.0](https://github.com/jborgers/sonar-pmd/tree/4.0.0) (2025-02-24)
+[Full Changelog](https://github.com/jborgers/sonar-pmd/compare/3.5.1..4.0.0)
+
+**Implemented highlights:**
+- Supports PMD 7 which is incompatible with PMD 6: the reason for a major release
+- Supports latest SonarQube [9.9.4 - 10.8+]
+- Supports running on Java 11 on analysis side for SQ 9.9.4 - 10.2.x
+- Supports running on Java 17 for all supported versions
+- Needed for child plugins with custom rules written in PMD 7, such as [sonar-pmd-jpinpoint 2.0.0](https://github.com/jborgers/sonar-pmd-jpinpoint/releases/tag/2.0.0)
+
+## [3.5.1](https://github.com/jborgers/sonar-pmd/tree/3.5.1) (2024-05-07)
+[Full Changelog](https://github.com/jborgers/sonar-pmd/compare/3.5.0..3.5.1)
+
+**Implemented highlights:**
+- Supports latest SonarQube [9.9.4 - 10.5+]
+- Supports running on Java 11 on analysis side for SQ 9.9.4 - 10.2.x
+- Supports running on Java 17 for all supported versions
+- Updated Sonar Plugin API+impl for SonarQube 9.9.4+
+- Upgraded various dependencies
+
+- ## [3.5.0](https://github.com/jborgers/sonar-pmd/tree/3.5.0) (2024-04-23)
+[Full Changelog](https://github.com/jborgers/sonar-pmd/compare/3.4.0...3.5.0)
+
+**Contributors:**
+- [jborgers](https://github.com/jborgers)
+- [renewolfert](https://github.com/renewolfert)
+
+**Implemented highlights:**
+- Updated PMD (6.55.0) (last PMD-6) #422
+- Support analyzing up to Java 20-preview (close to 21) #422
+- Java 21+ falls back to 20-preview with warning (no error) #422
+- Updated Sonar Plugin API+impl (9.8.0.63668) (SonarQube 9.8+)
+- Upgraded various dependencies
+- Needs Java 17, the class file version is 61
+
+## [3.4.0](https://github.com/jborgers/sonar-pmd/tree/3.4.0) (2022-05-11)
+[Full Changelog](https://github.com/jborgers/sonar-pmd/compare/3.3.1...3.4.0)
+
+**Contributors:**
+- [jborgers](https://github.com/jborgers)
+- [stokpop](https://github.com/stokpop)
+- [jensgerdes](https://github.com/jensgerdes) (Many thanks for his great maintenance and decision to transfer)
+
+**Implemented highlights:**
+- Updated PMD (6.45.0) #319
+- Support for Java 18 (including 17) #319
+- Updated Sonar Plugin API (9.4.0.54424) #309
+- Removed explicit dependency on Java plugin for new SonarQube Marketplace setup #303
+- Upgraded various dependencies
+- Transferred maintenance to [jborgers](https://github.com/jborgers) and [stokpop](https://github.com/stokpop)
+
+## [3.3.1](https://github.com/jensgerdes/sonar-pmd/tree/3.3.1) (2021-01-29)
+[Full Changelog](https://github.com/jensgerdes/sonar-pmd/compare/3.3.0...3.3.1)
+
+**Contributors:**
+- [jborgers](https://github.com/jborgers)
+
+**Closed issues:**
+- Fixed Windows incompatibility introduced in 3.3.0 [\#244](https://github.com/jensgerdes/sonar-pmd/issues/244)
+
+## [3.3.0](https://github.com/jensgerdes/sonar-pmd/tree/3.3.0) (2021-01-11)
+[Full Changelog](https://github.com/jensgerdes/sonar-pmd/compare/3.2.1...3.3.0)
+
+**Contributors:**
+- [jborgers](https://github.com/jborgers)
+- [robinverduijn](https://github.com/robinverduijn)
+
+**Implemented enhancements:**
+- Updated PMD (6.30.0)
+- Support for Java 15
+- Updated Sonar-Java API (6.0.1)
+
+**Closed issues:**
+- Fixed deprecated PMD API Usage [\#239](https://github.com/jensgerdes/sonar-pmd/issues/239)
+- Fixed CVE-2018-10237 [\#230](https://github.com/jensgerdes/sonar-pmd/issues/230)
+- Fixed incorrect rule description [\#78](https://github.com/jensgerdes/sonar-pmd/issues/78)
+
+**Merged pull requests:**
+- Move to pmd-6.29 and solve api incompatibility [\#228](https://github.com/jensgerdes/sonar-pmd/pull/228) ([jborgers](https://github.com/jborgers))
+- Update pmd-java dependency to 6.22.0 [\#167](https://github.com/jensgerdes/sonar-pmd/pull/167) ([robinverduijn](https://github.com/robinverduijn))
+- Use correct parent classloader to fix Java 9 style modules [\#168](https://github.com/jensgerdes/sonar-pmd/pull/168) ([robinverduijn](https://github.com/robinverduijn))
## [3.2.1](https://github.com/jensgerdes/sonar-pmd/tree/3.2.1) (2019-04-15)
[Full Changelog](https://github.com/jensgerdes/sonar-pmd/compare/3.2.0...3.2.1)
diff --git a/README.md b/README.md
index 31c62aa1..82650d47 100644
--- a/README.md
+++ b/README.md
@@ -1,48 +1,114 @@
-# SonarQube PMD Plugin [](https://maven-badges.herokuapp.com/maven-central/org.sonarsource.pmd/sonar-pmd-plugin) [](https://travis-ci.org/jensgerdes/sonar-pmd) [](https://sonarcloud.io/dashboard?id=org.sonarsource.pmd%3Asonar-pmd-plugin) [](https://sonarcloud.io/dashboard?id=org.sonarsource.pmd%3Asonar-pmd-plugin)
-Sonar-PMD is a plugin that provides coding rules from [PMD](https://pmd.github.io/).
+# SonarQube PMD Plugin
-For a list of all rules and their status, see: [RULES.md](https://github.com/jensgerdes/sonar-pmd/blob/master/docs/RULES.md)
+[](https://maven-badges.sml.io/sonatype-central/org.sonarsource.pmd/sonar-pmd-plugin)
+[](https://maven-badges.sml.io/maven-central/org.sonarsource.pmd/sonar-pmd-plugin)
+
+[](https://sonarcloud.io/summary/new_code?id=jborgers_sonar-pmd)
+
+Sonar-PMD is a plugin that provides coding rules from [PMD](https://pmd.github.io/) for use in SonarQube.
+
+Starting April 2022, the project has found a new home. We, [jborgers](https://github.com/jborgers) and [stokpop](https://github.com/stokpop),
+aim to provide an active project and well-maintained sonar-pmd plugin. It is now sponsored by [Rabobank](https://www.rabobank.com/).
## Installation
-The plugin is available in the SonarQube marketplace and should preferably be installed from within SonarQube (Administration --> Marketplace --> Search _pmd_).
+The plugin should be available in the SonarQube marketplace and is preferably installed from within SonarQube (Administration → Marketplace → Search _pmd_).
-Alternatively, download the [latest JAR file](https://github.com/jensgerdes/sonar-pmd/releases/latest), put it into the plugin directory (`./extensions/plugins`) and restart SonarQube.
+Alternatively, download the [latest JAR file](https://github.com/jborgers/sonar-pmd/releases/latest), put it into the plugin directory (`./extensions/downloads`) and restart SonarQube.
## Usage
Usage should be straight forward:
1. Activate some PMD rules in your quality profile.
2. Run an analysis.
-### Troubleshooting
+### PMD version
+Sonar PMD plugin version 4.0+ supports PMD 7 which is incompatible with PMD 6: the reason for a major release.
+Use version 4.0+ for child plugins with custom rules written in PMD 7, such as [sonar-pmd-jpinpoint 2.0.0](https://github.com/jborgers/sonar-pmd-jpinpoint/releases/tag/2.0.0).
+
+### Java version
Sonar-PMD analyzes the given source code with the Java source version defined in your Gradle or Maven project.
-In case you are not using one of these build tools, PMD uses the default Java version - which is **1.6**.
+In case you are not using one of these build tools, or if that does not match the version you are using, set the `sonar.java.source` property to tell PMD which version of Java your source code complies to.
+
+Possible values: 8 to 25 and 25-preview
+
+## Table of supported versions
+| Sonar-PMD Plugin | 3.5.0 | 3.5.1 | 4.0.0 | 4.0.3 | 4.1.0 | 4.2.0 |
+|------------------------|-----------------|-----------------|---------|------------|-------------|-------------------------------------------------------------------------|
+| PMD | 6.55.0 | 6.55.0 | 7.10.0 | 7.14.0 | 7.15.0 | [7.17.0](https://github.com/pmd/pmd/releases/tag/pmd_releases%2F7.17.0) |
+| Max. Java Version | 20-preview (*1) | 20-preview (*1) | 20 (*2) | 24-preview | 24-preview | 25-preview |
+| Min. SonarQube Version | 9.8 | 9.9.4 | 9.9.4 | 9.9.4 | 9.9.6 | 9.9.6 |
+| Max. SonarQube Version | 10.4 | 10.5+ | 10.8+ | 25.6+ | 25.6+ | 25.9+ |
+
+(*1) Note: Supports all tested Java 21 features; on parsing errors, warns instead of breaks.
+(*2) Note: Does not support Java 20-preview nor Java 21.
+
+## Limited Java PMD rule support before 4.1.0
+PMD rules created since PMD 5.5.0 in 2016 were missing in release 4.0.3 and before.
+
+Additionally, the sonar-pmd plugin marked the PMD rules which have a known adopted alternative in Sonar as `Deprecated`.
+Furthermore, PMD rules which were deprecated by PMD itself had the `Deprecated` mark as well, which was confusing.
+
+## Full Java PMD rule support starting with 4.1.0
+With version 4.1.0 we introduce easy incorporation of new PMD rules into this plugin and thereby support the full up-to-date set of PMD rules in Sonar.
+
+From now on, only rules that are deprecated in PMD are also marked `Deprecated` in Sonar. Rules that have alternative rules in Sonar are tagged with
+`has-sonar-alternative`, so they can be easily selected in SonarQube. The documentation will include the link to known alternative Sonar rule.
-If that does not match the version you are using, set the `sonar.java.source` property to tell PMD which version of Java your source code complies to.
+Limitations:
+1. Referred alternative Java Sonar rules are limited to rules from before 2016, newer Java Sonar rules are not referred to yet.
+If you find missing alternative rules please create a Github issue.
+2. The estimated amount of time to fix issues is only available for rules from before 2016.
+3. Properties of the rules cannot be changed via SonarQube, currently only defaults can be used.
-Possible values:
-- 1.4
-- 1.5 or 5
-- 1.6 or 6
-- 1.7 or 7
-- 1.8 or 8
-- 9
-- 10
-- 11
+## Java PMD rules summary
-## Description / Features
-PMD Plugin|2.0|2.1|2.2|2.3|2.4.1|2.5|2.6|3.0.0|3.1.x|3.2.x
--------|---|---|---|---|---|---|---|---|---|---
-PMD|4.3|4.3|5.1.1|5.2.1|5.3.1|5.4.0|5.4.2|5.4.2|6.9.0|6.10.0
-Max. supported Java Version | | | | | | 1.7 | 1.8 | 1.8 | 11 |
-Min. SonarQube Version | | | | | | 4.5.4 | 4.5.4 | 6.6 | 6.6 |
+- Total rules in old version (4.1.0): 282
+- Total rules in new version (4.2.0): 292
+- Rules added: 10
+- Rules removed: 0
+- Rules unchanged: 233
+- Rules updated: 49
+- Rules renamed: 10
-A majority of the PMD rules have been rewritten in the Java plugin. Rewritten rules are marked "Deprecated" in the PMD plugin, but a [concise summary of replaced rules](http://dist.sonarsource.com/reports/coverage/pmd.html) is available.
+See details: [pmd_release_notes_4.2.0.md](docs/pmd_release_notes_4.2.0.md)
-## Rules on test
-PMD tool provides some rules that can check the code of JUnit tests. Please note that these rules (and only these rules) will be applied only on the test files of your project.
+## Support for other languages
+Support for Apex PMD rules is work in progress.
+
+## Main vs Test sources and analysis scope
+SonarQube distinguishes between main source files and test source files.
+Sonar-PMD assigns a scope to each PMD rule so it runs only where it makes sense.
+
+How scope is set automatically:
+- Default: ALL (rule runs on both main and test sources).
+- If a rule name contains "Test" or "JUnit" (case-insensitive), it is treated as a test rule and scoped to TEST automatically.
+- Test rules get the `tests` Sonar tag conform existing Sonar test scoped rules.
+
+How to configure or override the scope in the PMD rules XML:
+1. Force a rule to run only on tests: add the tag `tests`.
+1. Force a rule to run only on main sources: add the tag `main-sources`.
+1. Force a rule run on ALL sources: add both tags `tests` and `main-sources`.
+
+Note that the latter two options will override the rule name matching the test pattern. Also, the `tests` tag will not be shown.
+
+Notes:
+- The PMD tag `main-sources` is used for scope control and is not shown in the rule tags list in SonarQube.
## License
-Sonar-PMD is licensed under the [GNU Lesser General Public License, Version 3.0](https://github.com/jensgerdes/sonar-pmd/blob/master/LICENSE.md).
+Sonar-PMD is licensed under the [GNU Lesser General Public License, Version 3.0](https://github.com/jborgers/sonar-pmd/blob/master/LICENSE.md).
Parts of the rule descriptions displayed in SonarQube have been extracted from [PMD](https://pmd.github.io/) and are licensed under a [BSD-style license](https://github.com/pmd/pmd/blob/master/LICENSE).
+## Build and test the plugin
+To build the plugin and run the integration tests (use java 17 to build the plugin):
+
+ ./mvnw clean verify
+
+## Generate PMD rules XML (Java and Kotlin)
+To regenerate the `rules-java.xml` and `rules-kotlin.xml` from PMD 7 using the provided Groovy script, run from the project root:
+
+ ./mvnw clean generate-resources -Pgenerate-pmd-rules -pl sonar-pmd-plugin -am
+
+Notes:
+- The `-am` (also-make) flag ensures dependent modules (e.g., `sonar-pmd-lib`) are built in the reactor even when building only `sonar-pmd-plugin` with `-pl`.
+- If `sonar-pmd-lib` fails to build so new changes are not reflected in the rules, try running `mvn clean package` in the `sonar-pmd-lib` module.
+
diff --git a/RELEASE.md b/RELEASE.md
new file mode 100644
index 00000000..9fc3108f
--- /dev/null
+++ b/RELEASE.md
@@ -0,0 +1,64 @@
+# Release Process
+
+This document describes the process for creating a new release of the SonarQube PMD plugin.
+
+## Prerequisites
+
+Before starting the release process:
+
+1. Ensure all commits have been pushed
+2. Verify the build passes with the `build.yml` GitHub Actions workflow
+3. In Github, close all issues and pull requests related to the new release x.y.z.
+
+## Preparation
+
+### Update PMD Rules and Generate Release Notes
+
+For updating PMD rules and generating release notes, refer to the [scripts documentation](scripts/README.md).
+
+In Github create a Draft release, or a pre-release.
+
+## Release Steps
+
+1. Update documentation:
+ - Create release notes in `CHANGELOG.md` (update `..master` to `..x.y.z`)
+ - Copy the commented out SNAPSHOT section to new SNAPSHOT release x.y.z+1-SNAPSHOT
+ - Uncomment the current SNAPSHOT release to non-SNAPSHOT upcoming release x.y.z
+ - Fill in the "Implemented highlights"
+ - Update `README.md` if needed
+ - Commit an push changes
+
+2. Publish the release in Github:
+ - Fill the to-be-created version
+ - Generate the release notes, sync with "Implemented highlights" from `CHANGELOG.md`
+ - Press Publish button
+
+ This will trigger the release workflow, which injects the git tag via maven `-Drevision= (\s*)This rule is deprecated, use \{rule:squid:(\w+)\} (.*)instead.(\s*)<\/p>/
-
- if (content =~ regex) {
- return content.replaceFirst(regex, "")
- }
-
- return content
-}
-
-def createMarkdownPagesForCategory = {
- category ->
- def currentDir = new File("${ruleSourcePath}/${category}")
- currentDir.eachFile FileType.FILES, {
- String rulename = it.name.tokenize('.')[0]
-
- println " * Processing Rule ${rulename}"
-
- String htmlContent = it.text
- String deprecationWarning = createDeprecationWarning(extractRulesFromContent(htmlContent))
- htmlContent = removeDeprecationMessage(htmlContent).trim()
- String ruleContent = """# ${rulename}
-**Category:** `${category}`
- The method
- Note that Oracle has declared
- Avoid constants in interfaces. Interfaces should define types, constants are implementation details better placed in
- classes or enums.
-
- See Effective Java, item 19.
-
- One might assume that the result of
- The (String) constructor, on the other hand, is perfectly predictable:
- Avoid using dollar signs in variable/method/class/interface names.
-
- This rule is deprecated, use {rule:squid:S00114}, {rule:squid:S00115}, {rule:squid:S00116} and {rule:squid:S00117}
- instead.
-
- Avoid throwing certain exception types. Rather than throw a raw RuntimeException, Throwable, Exception, or Error, use
- a subclassed exception or error instead.
-
- Class names should always begin with an upper case character.
-
- The java Manual says “By convention, classes that implement this interface should override Object.clone (which is
- protected) with a public method.”
- Examples: Minimum Language Version: java 1.5
- If a class implements cloneable the return type of the method clone() must be the class name. That way, the caller of
- the clone method doesn’t need to cast the returned clone to the correct type.
-
- Note: This is only possible with Java 1.5 or higher.
- Examples:
- To avoid mistakes if we want that a Method, Field or Nested class have a default access modifier
- we must add a comment at the beginning of the Method, Field or Nested class.
- By default the comment must be /* default */, if you want another, you have to provide a regex.
-
- Complexity is determined by the number of decision points in a method plus one for the method entry. The decision
- points are 'if', 'while', 'for', and 'case labels'. Generally, 1-4 is low complexity, 5-7 indicates moderate
- complexity, 8-10 is high complexity, and 11+ is very high complexity.
-
- Empty Catch Block finds instances where an exception is caught, but nothing is done. In most circumstances, this
- swallows an exception which should either be acted on or reported.
- If the finalize() method is empty, then it does not need to exist.
- Avoid empty finally blocks - these can be deleted.
-
- Empty If Statement finds instances where a condition is checked but nothing is done about it.
-
- Long parameter lists can indicate that a new object should be created to wrap the numerous parameters. Basically, try
- to group the parameters together.
-
- Avoid using 'for' statements without using curly braces, like
- Avoid using if..else statements without using curly braces.
-
- Avoid using if statements without using curly braces.
- Example:
- This rule is deprecated, use {rule:common-java:InsufficientCommentDensity} instead.
-
- Calls to a collection’s
- Previous versions of this rule (pre PMD 6.0.0) suggested the opposite, but current JVM implementations
- perform always better, when they have full control over the target array. And allocation an array via
- reflection is nowadays as fast as the direct allocation.
-
- See also Arrays of Wisdom of the Ancients
-
- Note: If you don’t need an array of the correct type, then the simple
- Look for ternary operators with the form condition ? literalBoolean : foo or condition ? foo : literalBoolean.
- Examples:
- Some classes contain overloaded getInstance. The problem with overloaded getInstance methods is that the instance
- created using the overloaded method is not cached and so, for each call and new objects will be created for every
- invocation.
- Examples:
- Some classes contain overloaded getInstance. The problem with overloaded getInstance methods is that the instance
- created using the overloaded method is not cached and so, for each call and new objects will be created for every
- invocation.
- Examples: Uncommented Empty Method finds instances where a method does not contain statements, but there is no comment. By
- explicitly commenting empty methods it is easier to distinguish between intentional (commented) and unintentional
- empty methods. Avoid passing parameters to methods or constructors and then not using those parameters.
- Unused Private Method detects when a private method is declared but is unused. This PMD rule should be switched off
- and replaced by its equivalent from Squid that is more effective : it generates less false-positives and detects more
- dead code.
- Look for qualified this usages in the same class. Examples:
- Avoid using 'while' statements without using curly braces.
-
- This rule is deprecated, please see the documentation on Extending
- Coding Rules.
- The abstract class does not contain any abstract methods. An abstract class suggests
+an incomplete implementation, which is to be completed by subclasses implementing the
+abstract methods. If the class is intended to be used as a base class only (not to be instantiated
+directly) a protected constructor can be provided to prevent direct instantiation.
-**Rule Key:** `${category}:${rulename}`
-${deprecationWarning}
-
------
-
-${htmlContent}
-"""
- def file = new File("${ruleTargetPath}/${rulename}.md").newWriter()
- file << ruleContent
- file.close()
- }
-}
-
-createMarkdownPagesForCategory('pmd')
-createMarkdownPagesForCategory('pmd-unit-tests')
\ No newline at end of file
diff --git a/docs/pmd_release_notes_4.1.0.md b/docs/pmd_release_notes_4.1.0.md
new file mode 100644
index 00000000..373a287b
--- /dev/null
+++ b/docs/pmd_release_notes_4.1.0.md
@@ -0,0 +1,339 @@
+# PMD Rules Release Notes for version 4.1.0
+_Do not edit this generated file._
+
+## Summary
+- Total rules in old version (4.0.3): 206
+- Total rules in new version (4.1.0): 282
+- Rules added: 80
+- Rules removed: 4
+- Rules unchanged: 46
+- Rules updated: 155
+- Rules renamed: 11
+
+## Added Rules
+The following rules have been added in the new version:
+
+| Rule Key | Name | Severity | Category |
+|----------|------|----------|----------|
+| AccessorMethodGeneration | Accessor method generation | Medium | bestpractices |
+| AvoidCalendarDateCreation | Avoid calendar date creation | Medium | performance |
+| AvoidFileStream | Avoid file stream | Blocker | performance |
+| AvoidMessageDigestField | Avoid message digest field | Medium | bestpractices |
+| AvoidReassigningCatchVariables | Avoid reassigning catch variables | Medium | bestpractices |
+| AvoidReassigningLoopVariables | Avoid reassigning loop variables | Medium | bestpractices |
+| AvoidSynchronizedStatement | Avoid synchronized statement | Medium | multithreading |
+| AvoidUncheckedExceptionsInSignatures | Avoid unchecked exceptions in signatures | Medium | design |
+| CloneMethodMustImplementCloneable | Clone method must implement cloneable | Medium | errorprone |
+| CognitiveComplexity | Cognitive complexity | Medium | design |
+| ComparisonWithNaN | Comparison with na n | Medium | errorprone |
+| ConfusingArgumentToVarargsMethod | Confusing argument to varargs method | Medium | errorprone |
+| ConstantsInInterface | Constants in interface | Medium | bestpractices |
+| ControlStatementBraces | Control statement braces | Medium | codestyle |
+| DataClass | Data class | Medium | design |
+| DefaultLabelNotLastInSwitch | Default label not last in switch | Medium | bestpractices |
+| DetachedTestCase | Detached test case | Medium | errorprone |
+| DoNotExtendJavaLangThrowable | Do not extend java lang throwable | Medium | errorprone |
+| DoNotTerminateVM | Do not terminate VM | Medium | errorprone |
+| DoubleBraceInitialization | Double brace initialization | Medium | bestpractices |
+| EmptyControlStatement | Empty control statement | Medium | codestyle |
+| ExhaustiveSwitchHasDefault | Exhaustive switch has default | Medium | bestpractices |
+| FieldNamingConventions | Field naming conventions | Blocker | codestyle |
+| FinalParameterInAbstractMethod | Final parameter in abstract method | Blocker | codestyle |
+| ForLoopCanBeForeach | For loop can be foreach | Medium | bestpractices |
+| ForLoopVariableCount | For loop variable count | Medium | bestpractices |
+| FormalParameterNamingConventions | Formal parameter naming conventions | Blocker | codestyle |
+| HardCodedCryptoKey | Hard coded crypto key | Medium | security |
+| IdenticalCatchBranches | Identical catch branches | Medium | codestyle |
+| ImplicitFunctionalInterface | Implicit functional interface | High | bestpractices |
+| ImplicitSwitchFallThrough | Implicit switch fall through | Medium | errorprone |
+| InsecureCryptoIv | Insecure crypto iv | Medium | security |
+| InvalidJavaBean | Invalid java bean | Medium | design |
+| InvalidLogMessageFormat | Invalid log message format | Info | errorprone |
+| JUnit4SuitesShouldUseSuiteAnnotation | JUnit4 suites should use suite annotation | Medium | bestpractices |
+| JUnit5TestShouldBePackagePrivate | JUnit5 test should be package private | Medium | bestpractices |
+| JUnitSpelling | JUnit spelling | Medium | errorprone |
+| JUnitStaticSuite | JUnit static suite | Medium | errorprone |
+| JUnitUseExpected | JUnit use expected | Medium | bestpractices |
+| LambdaCanBeMethodReference | Lambda can be method reference | Medium | codestyle |
+| LinguisticNaming | Linguistic naming | Medium | codestyle |
+| LiteralsFirstInComparisons | Literals first in comparisons | Medium | bestpractices |
+| LocalVariableNamingConventions | Local variable naming conventions | Blocker | codestyle |
+| LooseCoupling | Loose coupling | Medium | bestpractices |
+| MissingOverride | Missing override | Medium | bestpractices |
+| MutableStaticState | Mutable static state | Medium | design |
+| NcssCount | Ncss count | Medium | design |
+| NonCaseLabelInSwitch | Non case label in switch | Medium | errorprone |
+| NonExhaustiveSwitch | Non exhaustive switch | Medium | bestpractices |
+| NonSerializableClass | Non serializable class | Medium | errorprone |
+| PrimitiveWrapperInstantiation | Primitive wrapper instantiation | Medium | bestpractices |
+| ReturnEmptyCollectionRatherThanNull | Return empty collection rather than null | Blocker | errorprone |
+| SimplifiableTestAssertion | Simplifiable test assertion | Medium | bestpractices |
+| TestClassWithoutTestCases | Test class without test cases | Medium | errorprone |
+| TooFewBranchesForSwitch | Too few branches for switch | Medium | performance |
+| UnitTestAssertionsShouldIncludeMessage | Unit test assertions should include message | Medium | bestpractices |
+| UnitTestContainsTooManyAsserts | Unit test contains too many asserts | Medium | bestpractices |
+| UnitTestShouldIncludeAssert | Unit test should include assert | Medium | bestpractices |
+| UnitTestShouldUseAfterAnnotation | Unit test should use after annotation | Medium | bestpractices |
+| UnitTestShouldUseBeforeAnnotation | Unit test should use before annotation | Medium | bestpractices |
+| UnitTestShouldUseTestAnnotation | Unit test should use test annotation | Medium | bestpractices |
+| UnnecessaryAnnotationValueElement | Unnecessary annotation value element | Medium | codestyle |
+| UnnecessaryBooleanAssertion | Unnecessary boolean assertion | Medium | errorprone |
+| UnnecessaryBoxing | Unnecessary boxing | Medium | codestyle |
+| UnnecessaryCast | Unnecessary cast | Medium | codestyle |
+| UnnecessaryImport | Unnecessary import | Low | codestyle |
+| UnnecessaryModifier | Unnecessary modifier | Medium | codestyle |
+| UnnecessarySemicolon | Unnecessary semicolon | Medium | codestyle |
+| UnnecessaryVarargsArrayCreation | Unnecessary varargs array creation | Medium | bestpractices |
+| UnnecessaryWarningSuppression | Unnecessary warning suppression | Medium | bestpractices |
+| UnsynchronizedStaticFormatter | Unsynchronized static formatter | Medium | multithreading |
+| UseDiamondOperator | Use diamond operator | Medium | codestyle |
+| UseEnumCollections | Use enum collections | Medium | bestpractices |
+| UseExplicitTypes | Use explicit types | Medium | codestyle |
+| UseIOStreamsWithApacheCommonsFileItem | Use IOStreams with apache commons file item | Medium | performance |
+| UseShortArrayInitializer | Use short array initializer | Medium | codestyle |
+| UseStandardCharsets | Use standard charsets | Medium | bestpractices |
+| UseTryWithResources | Use try with resources | Medium | bestpractices |
+| UseUnderscoresInNumericLiterals | Use underscores in numeric literals | Medium | codestyle |
+| WhileLoopWithLiteralBoolean | While loop with literal boolean | Medium | bestpractices |
+
+## Updated Rules
+The following rules have been updated in the new version:
+
+| Rule Key | Name | Old Priority | New Severity | Old Status | New Status | Alternatives | Category |
+|----------|------|--------------|--------------|------------|------------|--------------|----------|
+| AbstractClassWithoutAbstractMethod | Abstract class without abstract method | | Medium | Deprecated | Active | [java:S1694](https://rules.sonarsource.com/java/RSPEC-1694) | bestpractices |
+| AbstractClassWithoutAnyMethod | Abstract class without any method | Medium | Blocker | Deprecated | Active | [java:S1694](https://rules.sonarsource.com/java/RSPEC-1694) | design |
+| AppendCharacterWithChar | Append character with char | Low | Medium | | Active | | performance |
+| ArrayIsStoredDirectly | Array is stored directly | High | Medium | Deprecated | Active | [java:S2384](https://rules.sonarsource.com/java/RSPEC-2384) | bestpractices |
+| AssignmentInOperand | Assignment in operand | | Medium | Deprecated | Active | [java:S1121](https://rules.sonarsource.com/java/RSPEC-1121) | errorprone |
+| AtLeastOneConstructor | At least one constructor | | Medium | Deprecated | Active | [java:S1118](https://rules.sonarsource.com/java/RSPEC-1118), [java:S1258](https://rules.sonarsource.com/java/RSPEC-1258) | codestyle |
+| AvoidAssertAsIdentifier | Avoid assert as identifier | Medium | High | Deprecated | Active | [java:S1190](https://rules.sonarsource.com/java/RSPEC-1190) | errorprone |
+| AvoidBranchingStatementAsLastInLoop | Avoid branching statement as last in loop | Medium | High | | Active | | errorprone |
+| AvoidCallingFinalize | Avoid calling finalize | | Medium | Deprecated | Active | | errorprone |
+| AvoidCatchingGenericException | Avoid catching generic exception | | Medium | Deprecated | Active | [java:S2221](https://rules.sonarsource.com/java/RSPEC-2221) | design |
+| AvoidCatchingNPE | Avoid catching NPE | | Medium | Deprecated | Active | [java:S1696](https://rules.sonarsource.com/java/RSPEC-1696) | errorprone |
+| AvoidCatchingThrowable | Avoid catching throwable | High | Medium | Deprecated | Active | [java:S1181](https://rules.sonarsource.com/java/RSPEC-1181) | errorprone |
+| AvoidDecimalLiteralsInBigDecimalConstructor | Avoid decimal literals in big decimal constructor | | Medium | Deprecated | Active | [java:S2111](https://rules.sonarsource.com/java/RSPEC-2111) | errorprone |
+| AvoidDeeplyNestedIfStmts | Avoid deeply nested if stmts | | Medium | Deprecated | Active | [java:S134](https://rules.sonarsource.com/java/RSPEC-134) | design |
+| AvoidDollarSigns | Avoid dollar signs | Low | Medium | Deprecated | Active | [java:S114](https://rules.sonarsource.com/java/RSPEC-114), [java:S115](https://rules.sonarsource.com/java/RSPEC-115), [java:S116](https://rules.sonarsource.com/java/RSPEC-116), [java:S117](https://rules.sonarsource.com/java/RSPEC-117) | codestyle |
+| AvoidDuplicateLiterals | Avoid duplicate literals | | Medium | Deprecated | Active | [java:S1192](https://rules.sonarsource.com/java/RSPEC-1192) | errorprone |
+| AvoidEnumAsIdentifier | Avoid enum as identifier | Medium | High | Deprecated | Active | [java:S1190](https://rules.sonarsource.com/java/RSPEC-1190) | errorprone |
+| AvoidFieldNameMatchingMethodName | Avoid field name matching method name | | Medium | Deprecated | Active | [java:S1845](https://rules.sonarsource.com/java/RSPEC-1845) | errorprone |
+| AvoidFieldNameMatchingTypeName | Avoid field name matching type name | | Medium | Deprecated | Active | [java:S1700](https://rules.sonarsource.com/java/RSPEC-1700) | errorprone |
+| AvoidInstanceofChecksInCatchClause | Avoid instanceof checks in catch clause | Low | Medium | Deprecated | Active | [java:S1193](https://rules.sonarsource.com/java/RSPEC-1193) | errorprone |
+| AvoidInstantiatingObjectsInLoops | Avoid instantiating objects in loops | Low | Medium | | Active | | performance |
+| AvoidLiteralsInIfCondition | Avoid literals in if condition | | Medium | Deprecated | Active | [java:S109](https://rules.sonarsource.com/java/RSPEC-109) | errorprone |
+| AvoidLosingExceptionInformation | Avoid losing exception information | Medium | High | Deprecated | Active | [java:S1166](https://rules.sonarsource.com/java/RSPEC-1166) | errorprone |
+| AvoidMultipleUnaryOperators | Avoid multiple unary operators | Medium | High | Deprecated | Active | [java:S881](https://rules.sonarsource.com/java/RSPEC-881) | errorprone |
+| AvoidPrintStackTrace | Avoid print stack trace | | Medium | Deprecated | Active | [java:S1148](https://rules.sonarsource.com/java/RSPEC-1148) | bestpractices |
+| AvoidProtectedFieldInFinalClass | Avoid protected field in final class | | Medium | Deprecated | Active | [java:S2156](https://rules.sonarsource.com/java/RSPEC-2156) | codestyle |
+| AvoidProtectedMethodInFinalClassNotExtending | Avoid protected method in final class not extending | | Medium | Deprecated | Active | [java:S2156](https://rules.sonarsource.com/java/RSPEC-2156) | codestyle |
+| AvoidReassigningParameters | Avoid reassigning parameters | Medium | High | Deprecated | Active | [java:S1226](https://rules.sonarsource.com/java/RSPEC-1226) | bestpractices |
+| AvoidRethrowingException | Avoid rethrowing exception | | Medium | Deprecated | Active | [java:S1166](https://rules.sonarsource.com/java/RSPEC-1166) | design |
+| AvoidStringBufferField | Avoid string buffer field | | Medium | Deprecated | Active | [java:S1149](https://rules.sonarsource.com/java/RSPEC-1149) | bestpractices |
+| AvoidThreadGroup | Avoid thread group | High | Medium | | Active | | multithreading |
+| AvoidThrowingNewInstanceOfSameException | Avoid throwing new instance of same exception | | Medium | Deprecated | Active | [java:S1166](https://rules.sonarsource.com/java/RSPEC-1166) | design |
+| AvoidThrowingNullPointerException | Avoid throwing null pointer exception | Medium | Blocker | Deprecated | Active | [java:S1695](https://rules.sonarsource.com/java/RSPEC-1695) | design |
+| AvoidThrowingRawExceptionTypes | Avoid throwing raw exception types | Medium | Blocker | Deprecated | Active | [java:S112](https://rules.sonarsource.com/java/RSPEC-112) | design |
+| AvoidUsingHardCodedIP | Avoid using hard coded IP | | Medium | Deprecated | Active | [java:S1313](https://rules.sonarsource.com/java/RSPEC-1313) | bestpractices |
+| AvoidUsingNativeCode | Avoid using native code | Medium | High | | Active | | codestyle |
+| AvoidUsingOctalValues | Avoid using octal values | | Medium | Deprecated | Active | [java:S1314](https://rules.sonarsource.com/java/RSPEC-1314) | errorprone |
+| AvoidUsingVolatile | Avoid using volatile | Medium | High | | Active | | multithreading |
+| BooleanGetMethodName | Boolean get method name | Medium | Low | | Active | | codestyle |
+| BrokenNullCheck | Broken null check | | High | Deprecated | Active | [java:S1697](https://rules.sonarsource.com/java/RSPEC-1697) | errorprone |
+| CallSuperInConstructor | Call super in constructor | Low | Medium | | Active | | codestyle |
+| CheckSkipResult | Check skip result | Low | Medium | Deprecated | Active | [java:S2674](https://rules.sonarsource.com/java/RSPEC-2674) | errorprone |
+| ClassNamingConventions | Class naming conventions | Medium | Blocker | Deprecated | Active | [java:S101](https://rules.sonarsource.com/java/RSPEC-101), [java:S114](https://rules.sonarsource.com/java/RSPEC-114) | codestyle |
+| ClassWithOnlyPrivateConstructorsShouldBeFinal | Class with only private constructors should be final | Medium | Blocker | Deprecated | Active | [java:S2974](https://rules.sonarsource.com/java/RSPEC-2974) | design |
+| CloseResource | Close resource | High | Medium | Deprecated | Active | [java:S2095](https://rules.sonarsource.com/java/RSPEC-2095) | errorprone |
+| CollapsibleIfStatements | Collapsible if statements | Low | Medium | Deprecated | Active | [java:S1066](https://rules.sonarsource.com/java/RSPEC-1066) | design |
+| CommentContent | Comment content | Low | Medium | | Active | | documentation |
+| CommentRequired | Comment required | Low | Medium | | Active | | documentation |
+| CommentSize | Comment size | Low | Medium | | Active | | documentation |
+| CompareObjectsWithEquals | Compare objects with equals | | Medium | Deprecated | Active | [java:S1698](https://rules.sonarsource.com/java/RSPEC-1698) | errorprone |
+| ConsecutiveLiteralAppends | Consecutive literal appends | Low | Medium | | Active | | performance |
+| ConstructorCallsOverridableMethod | Constructor calls overridable method | Medium | Blocker | Deprecated | Active | [java:S1699](https://rules.sonarsource.com/java/RSPEC-1699) | errorprone |
+| CouplingBetweenObjects | Coupling between objects | | Medium | Deprecated | Active | [java:S1200](https://rules.sonarsource.com/java/RSPEC-1200) | design |
+| CyclomaticComplexity | Cyclomatic complexity | | Medium | Deprecated | Active | [java:S1541](https://rules.sonarsource.com/java/RSPEC-1541) | design |
+| DoNotCallGarbageCollectionExplicitly | Do not call garbage collection explicitly | | High | Deprecated | Active | [java:S1215](https://rules.sonarsource.com/java/RSPEC-1215) | errorprone |
+| DoNotExtendJavaLangError | Do not extend java lang error | | Medium | Deprecated | Active | [java:S1194](https://rules.sonarsource.com/java/RSPEC-1194) | design |
+| DoNotThrowExceptionInFinally | Do not throw exception in finally | Medium | Low | Deprecated | Active | [java:S1163](https://rules.sonarsource.com/java/RSPEC-1163) | errorprone |
+| DontCallThreadRun | Dont call thread run | Medium | Low | Deprecated | Active | [java:S1217](https://rules.sonarsource.com/java/RSPEC-1217) | multithreading |
+| DontImportSun | Dont import sun | | Low | Deprecated | Active | [java:S1191](https://rules.sonarsource.com/java/RSPEC-1191) | errorprone |
+| DoubleCheckedLocking | Double checked locking | Medium | Blocker | | Active | | multithreading |
+| EmptyCatchBlock | Empty catch block | High | Medium | Deprecated | Active | [java:S108](https://rules.sonarsource.com/java/RSPEC-108) | errorprone |
+| EmptyFinalizer | Empty finalizer | | Medium | Deprecated | Active | [java:S1186](https://rules.sonarsource.com/java/RSPEC-1186) | errorprone |
+| EmptyMethodInAbstractClassShouldBeAbstract | Empty method in abstract class should be abstract | Medium | Blocker | | Active | | codestyle |
+| EqualsNull | Equals null | High | Blocker | Deprecated | Active | [java:S2159](https://rules.sonarsource.com/java/RSPEC-2159) | errorprone |
+| ExceptionAsFlowControl | Exception as flow control | | Medium | Deprecated | Active | [java:S1141](https://rules.sonarsource.com/java/RSPEC-1141) | design |
+| ExcessiveImports | Excessive imports | | Medium | Deprecated | Active | [java:S1200](https://rules.sonarsource.com/java/RSPEC-1200) | design |
+| ExcessiveParameterList | Excessive parameter list | | Medium | Deprecated | Active | [java:S107](https://rules.sonarsource.com/java/RSPEC-107) | design |
+| ExcessivePublicCount | Excessive public count | | Medium | Deprecated | Active | [java:S1448](https://rules.sonarsource.com/java/RSPEC-1448) | design |
+| ExtendsObject | Extends object | | Low | Deprecated | Active | [java:S1939](https://rules.sonarsource.com/java/RSPEC-1939) | codestyle |
+| FieldDeclarationsShouldBeAtStartOfClass | Field declarations should be at start of class | Low | Medium | Deprecated | Active | [java:S1213](https://rules.sonarsource.com/java/RSPEC-1213) | codestyle |
+| FinalFieldCouldBeStatic | Final field could be static | Low | Medium | Deprecated | Active | [java:S1170](https://rules.sonarsource.com/java/RSPEC-1170) | design |
+| FinalizeDoesNotCallSuperFinalize | Finalize does not call super finalize | | Medium | Deprecated | Active | | errorprone |
+| FinalizeOnlyCallsSuperFinalize | Finalize only calls super finalize | | Medium | Deprecated | Active | [java:S1185](https://rules.sonarsource.com/java/RSPEC-1185) | errorprone |
+| FinalizeOverloaded | Finalize overloaded | | Medium | Deprecated | Active | [java:S1175](https://rules.sonarsource.com/java/RSPEC-1175) | errorprone |
+| FinalizeShouldBeProtected | Finalize should be protected | | Medium | Deprecated | Active | [java:S1174](https://rules.sonarsource.com/java/RSPEC-1174) | errorprone |
+| ForLoopShouldBeWhileLoop | For loop should be while loop | Low | Medium | Deprecated | Active | [java:S1264](https://rules.sonarsource.com/java/RSPEC-1264) | codestyle |
+| GenericsNaming | Generics naming | Medium | Low | Deprecated | Active | [java:S119](https://rules.sonarsource.com/java/RSPEC-119) | codestyle |
+| IdempotentOperations | Idempotent operations | | Medium | Deprecated | Active | [java:S1656](https://rules.sonarsource.com/java/RSPEC-1656) | errorprone |
+| InstantiationToGetClass | Instantiation to get class | Medium | Low | Deprecated | Active | [java:S2133](https://rules.sonarsource.com/java/RSPEC-2133) | errorprone |
+| JumbledIncrementer | Jumbled incrementer | | Medium | Deprecated | Active | [java:S1994](https://rules.sonarsource.com/java/RSPEC-1994) | errorprone |
+| LocalHomeNamingConvention | Local home naming convention | Medium | Low | | Active | | codestyle |
+| LocalInterfaceSessionNamingConvention | Local interface session naming convention | Medium | Low | | Active | | codestyle |
+| LocalVariableCouldBeFinal | Local variable could be final | Low | Medium | | Active | | codestyle |
+| LogicInversion | Logic inversion | Low | Medium | Deprecated | Active | [java:S1940](https://rules.sonarsource.com/java/RSPEC-1940) | design |
+| LongVariable | Long variable | | Medium | Deprecated | Active | [java:S117](https://rules.sonarsource.com/java/RSPEC-117) | codestyle |
+| LoosePackageCoupling | Loose package coupling | | Medium | Deprecated | Active | | design |
+| MDBAndSessionBeanNamingConvention | MDBAnd session bean naming convention | Medium | Low | | Active | | codestyle |
+| MethodArgumentCouldBeFinal | Method argument could be final | Low | Medium | Deprecated | Active | [java:S1226](https://rules.sonarsource.com/java/RSPEC-1226) | codestyle |
+| MethodNamingConventions | Method naming conventions | Medium | Blocker | Deprecated | Active | [java:S100](https://rules.sonarsource.com/java/RSPEC-100) | codestyle |
+| MethodReturnsInternalArray | Method returns internal array | High | Medium | Deprecated | Active | [java:S2384](https://rules.sonarsource.com/java/RSPEC-2384) | bestpractices |
+| MethodWithSameNameAsEnclosingClass | Method with same name as enclosing class | | Medium | Deprecated | Active | [java:S1223](https://rules.sonarsource.com/java/RSPEC-1223) | errorprone |
+| MisplacedNullCheck | Misplaced null check | High | Medium | Deprecated | Active | [java:S1697](https://rules.sonarsource.com/java/RSPEC-1697), [java:S2259](https://rules.sonarsource.com/java/RSPEC-2259) | errorprone |
+| MissingSerialVersionUID | Missing serial version UID | | Medium | Deprecated | Active | [java:S2057](https://rules.sonarsource.com/java/RSPEC-2057) | errorprone |
+| MoreThanOneLogger | More than one logger | Medium | High | Deprecated | Active | [java:S1312](https://rules.sonarsource.com/java/RSPEC-1312) | errorprone |
+| NoPackage | No package | | Medium | Deprecated | Active | [java:S1220](https://rules.sonarsource.com/java/RSPEC-1220) | codestyle |
+| NonStaticInitializer | Non static initializer | | Medium | Deprecated | Active | [java:S1171](https://rules.sonarsource.com/java/RSPEC-1171) | errorprone |
+| NonThreadSafeSingleton | Non thread safe singleton | | Medium | Deprecated | Active | [java:S2444](https://rules.sonarsource.com/java/RSPEC-2444) | multithreading |
+| OneDeclarationPerLine | One declaration per line | Medium | Low | Deprecated | Active | [java:S122](https://rules.sonarsource.com/java/RSPEC-122) | bestpractices |
+| OnlyOneReturn | Only one return | Low | Medium | Deprecated | Active | [java:S1142](https://rules.sonarsource.com/java/RSPEC-1142) | codestyle |
+| OverrideBothEqualsAndHashcode | Override both equals and hashcode | Blocker | Medium | Deprecated | Active | [java:S1206](https://rules.sonarsource.com/java/RSPEC-1206) | errorprone |
+| PackageCase | Package case | | Medium | Deprecated | Active | [java:S120](https://rules.sonarsource.com/java/RSPEC-120) | codestyle |
+| PrematureDeclaration | Premature declaration | | Medium | Deprecated | Active | [java:S1941](https://rules.sonarsource.com/java/RSPEC-1941) | codestyle |
+| PreserveStackTrace | Preserve stack trace | | Medium | Deprecated | Active | [java:S1166](https://rules.sonarsource.com/java/RSPEC-1166) | bestpractices |
+| ProperCloneImplementation | Proper clone implementation | | High | Deprecated | Active | [java:S1182](https://rules.sonarsource.com/java/RSPEC-1182) | errorprone |
+| ProperLogger | Proper logger | | Medium | Deprecated | Active | [java:S1312](https://rules.sonarsource.com/java/RSPEC-1312) | errorprone |
+| RemoteInterfaceNamingConvention | Remote interface naming convention | Medium | Low | | Active | | codestyle |
+| RemoteSessionInterfaceNamingConvention | Remote session interface naming convention | Medium | Low | | Active | | codestyle |
+| ReplaceEnumerationWithIterator | Replace enumeration with iterator | | Medium | Deprecated | Active | [java:S1150](https://rules.sonarsource.com/java/RSPEC-1150) | bestpractices |
+| ReplaceHashtableWithMap | Replace hashtable with map | | Medium | Deprecated | Active | [java:S1149](https://rules.sonarsource.com/java/RSPEC-1149) | bestpractices |
+| ReplaceVectorWithList | Replace vector with list | | Medium | Deprecated | Active | [java:S1149](https://rules.sonarsource.com/java/RSPEC-1149) | bestpractices |
+| ReturnFromFinallyBlock | Return from finally block | | Medium | Deprecated | Active | [java:S1143](https://rules.sonarsource.com/java/RSPEC-1143) | errorprone |
+| ShortClassName | Short class name | | Low | Deprecated | Active | [java:S101](https://rules.sonarsource.com/java/RSPEC-101) | codestyle |
+| ShortMethodName | Short method name | | Medium | Deprecated | Active | [java:S100](https://rules.sonarsource.com/java/RSPEC-100) | codestyle |
+| ShortVariable | Short variable | | Medium | Deprecated | Active | [java:S117](https://rules.sonarsource.com/java/RSPEC-117) | codestyle |
+| SignatureDeclareThrowsException | Signature declare throws exception | | Medium | Deprecated | Active | [java:S112](https://rules.sonarsource.com/java/RSPEC-112) | design |
+| SimplifyBooleanExpressions | Simplify boolean expressions | | Medium | Deprecated | Active | [java:S1125](https://rules.sonarsource.com/java/RSPEC-1125) | design |
+| SimplifyBooleanReturns | Simplify boolean returns | Low | Medium | Deprecated | Active | [java:S1126](https://rules.sonarsource.com/java/RSPEC-1126) | design |
+| SingletonClassReturningNewInstance | Singleton class returning new instance | Medium | High | | Active | | errorprone |
+| SingularField | Singular field | Low | Medium | | Active | | design |
+| StringBufferInstantiationWithChar | String buffer instantiation with char | Medium | Low | Deprecated | Active | [java:S1317](https://rules.sonarsource.com/java/RSPEC-1317) | errorprone |
+| StringInstantiation | String instantiation | Medium | High | | Active | | performance |
+| StringToString | String to string | | Medium | Deprecated | Active | [java:S1858](https://rules.sonarsource.com/java/RSPEC-1858) | performance |
+| SuspiciousEqualsMethodName | Suspicious equals method name | | High | Deprecated | Active | [java:S1201](https://rules.sonarsource.com/java/RSPEC-1201) | errorprone |
+| SuspiciousHashcodeMethodName | Suspicious hashcode method name | | Medium | Deprecated | Active | [java:S1221](https://rules.sonarsource.com/java/RSPEC-1221) | errorprone |
+| SwitchDensity | Switch density | | Medium | Deprecated | Active | [java:S1151](https://rules.sonarsource.com/java/RSPEC-1151) | design |
+| SystemPrintln | System println | Medium | High | Deprecated | Active | [java:S106](https://rules.sonarsource.com/java/RSPEC-106) | bestpractices |
+| TooManyMethods | Too many methods | | Medium | Deprecated | Active | [java:S1448](https://rules.sonarsource.com/java/RSPEC-1448) | design |
+| UncommentedEmptyConstructor | Uncommented empty constructor | | Medium | Deprecated | Active | [java:S2094](https://rules.sonarsource.com/java/RSPEC-2094) | documentation |
+| UncommentedEmptyMethodBody | Uncommented empty method body | | Medium | Deprecated | Active | [java:S1186](https://rules.sonarsource.com/java/RSPEC-1186) | documentation |
+| UnconditionalIfStatement | Unconditional if statement | High | Medium | Deprecated | Active | [java:S2583](https://rules.sonarsource.com/java/RSPEC-2583) | errorprone |
+| UnnecessaryCaseChange | Unnecessary case change | Low | Medium | Deprecated | Active | [java:S1157](https://rules.sonarsource.com/java/RSPEC-1157) | errorprone |
+| UnnecessaryConstructor | Unnecessary constructor | | Medium | Deprecated | Active | [java:S1186](https://rules.sonarsource.com/java/RSPEC-1186) | codestyle |
+| UnnecessaryConversionTemporary | Unnecessary conversion temporary | | Medium | Deprecated | Active | [java:S1158](https://rules.sonarsource.com/java/RSPEC-1158) | errorprone |
+| UnnecessaryFullyQualifiedName | Unnecessary fully qualified name | Medium | Low | | Active | | codestyle |
+| UnnecessaryLocalBeforeReturn | Unnecessary local before return | | Medium | Deprecated | Active | [java:S1488](https://rules.sonarsource.com/java/RSPEC-1488) | codestyle |
+| UnnecessaryReturn | Unnecessary return | Low | Medium | | Active | | codestyle |
+| UnusedFormalParameter | Unused formal parameter | | Medium | Deprecated | Active | [java:S1172](https://rules.sonarsource.com/java/RSPEC-1172) | bestpractices |
+| UnusedLocalVariable | Unused local variable | | Medium | Deprecated | Active | [java:S1481](https://rules.sonarsource.com/java/RSPEC-1481) | bestpractices |
+| UnusedPrivateField | Unused private field | | Medium | Deprecated | Active | [java:S1068](https://rules.sonarsource.com/java/RSPEC-1068) | bestpractices |
+| UnusedPrivateMethod | Unused private method | | Medium | Deprecated | Active | | bestpractices |
+| UseArrayListInsteadOfVector | Use array list instead of vector | | Medium | Deprecated | Active | [java:S1149](https://rules.sonarsource.com/java/RSPEC-1149) | performance |
+| UseCollectionIsEmpty | Use collection is empty | Low | Medium | Deprecated | Active | [java:S1155](https://rules.sonarsource.com/java/RSPEC-1155) | bestpractices |
+| UseCorrectExceptionLogging | Use correct exception logging | | Medium | Deprecated | Active | [java:S1166](https://rules.sonarsource.com/java/RSPEC-1166) | errorprone |
+| UseEqualsToCompareStrings | Use equals to compare strings | | Medium | Deprecated | Active | [java:S1698](https://rules.sonarsource.com/java/RSPEC-1698) | errorprone |
+| UseNotifyAllInsteadOfNotify | Use notify all instead of notify | | Medium | Deprecated | Active | [java:S2446](https://rules.sonarsource.com/java/RSPEC-2446) | multithreading |
+| UseObjectForClearerAPI | Use object for clearer API | Low | Medium | Deprecated | Active | [java:S107](https://rules.sonarsource.com/java/RSPEC-107) | design |
+| UseProperClassLoader | Use proper class loader | High | Medium | | Active | | errorprone |
+| UseStringBufferLength | Use string buffer length | Low | Medium | | Active | | performance |
+| UseUtilityClass | Use utility class | | Medium | Deprecated | Active | [java:S1118](https://rules.sonarsource.com/java/RSPEC-1118) | design |
+| UseVarargs | Use varargs | Medium | Low | | Active | | bestpractices |
+| UselessOperationOnImmutable | Useless operation on immutable | High | Medium | | Active | | errorprone |
+| UselessOverridingMethod | Useless overriding method | | Medium | Deprecated | Active | [java:S1185](https://rules.sonarsource.com/java/RSPEC-1185) | design |
+| UselessParentheses | Useless parentheses | Info | Low | Deprecated | Active | [java:S1110](https://rules.sonarsource.com/java/RSPEC-1110) | codestyle |
+| UselessStringValueOf | Useless string value of | Low | Medium | Deprecated | Active | [java:S1153](https://rules.sonarsource.com/java/RSPEC-1153) | performance |
+| XPathRule | XPath rule | Medium | | Deprecated | Active | | |
+
+## Unchanged Rules
+The following rules exist in both versions with no changes:
+
+| Rule Key | Name | Severity | Status | Alternatives | Category |
+|----------|------|----------|--------|--------------|----------|
+| AccessorClassGeneration | Accessor class generation | Medium | Active | | bestpractices |
+| AddEmptyString | Add empty string | Medium | Active | | performance |
+| AssignmentToNonFinalStatic | Assignment to non final static | Medium | Active | | errorprone |
+| AvoidAccessibilityAlteration | Avoid accessibility alteration | Medium | Active | | errorprone |
+| AvoidArrayLoops | Avoid array loops | Medium | Active | | performance |
+| AvoidSynchronizedAtMethodLevel | Avoid synchronized at method level | Medium | Active | | multithreading |
+| BigIntegerInstantiation | Big integer instantiation | Medium | Active | | performance |
+| CallSuperFirst | Call super first | Medium | Active | | errorprone |
+| CallSuperLast | Call super last | Medium | Active | | errorprone |
+| CheckResultSet | Check result set | Medium | Active | | bestpractices |
+| ClassCastExceptionWithToArray | Class cast exception with to array | Medium | Active | | errorprone |
+| CloneMethodMustBePublic | Clone method must be public | Medium | Active | | errorprone |
+| CloneMethodReturnTypeMustMatchClassName | Clone method return type must match class name | Medium | Active | | errorprone |
+| CommentDefaultAccessModifier | Comment default access modifier | Medium | Active | | codestyle |
+| ConfusingTernary | Confusing ternary | Medium | Active | | codestyle |
+| ConsecutiveAppendsShouldReuse | Consecutive appends should reuse | Medium | Active | | performance |
+| DoNotHardCodeSDCard | Do not hard code SDCard | Medium | Active | | errorprone |
+| DoNotUseThreads | Do not use threads | Medium | Active | | multithreading |
+| DontUseFloatTypeForLoopIndices | Dont use float type for loop indices | Medium | Active | | errorprone |
+| GodClass | God class | Medium | Active | | design |
+| ImmutableField | Immutable field | Medium | Active | | design |
+| InefficientEmptyStringCheck | Inefficient empty string check | Medium | Active | | performance |
+| InefficientStringBuffering | Inefficient string buffering | Medium | Active | | performance |
+| InsufficientStringBufferDeclaration | Insufficient string buffer declaration | Medium | Active | | performance |
+| LawOfDemeter | Law of demeter | Medium | Active | | design |
+| MissingStaticMethodInNonInstantiatableClass | Missing static method in non instantiatable class | Medium | Active | | errorprone |
+| NPathComplexity | NPath complexity | Medium | Active | | design |
+| NullAssignment | Null assignment | Medium | Active | | errorprone |
+| OptimizableToArrayCall | Optimizable to array call | Medium | Active | | performance |
+| RedundantFieldInitializer | Redundant field initializer | Medium | Active | | performance |
+| SimpleDateFormatNeedsLocale | Simple date format needs locale | Medium | Active | | errorprone |
+| SimplifiedTernary | Simplified ternary | Medium | Active | | design |
+| SimplifyConditional | Simplify conditional | Medium | Active | | design |
+| SingleMethodSingleton | Single method singleton | High | Active | | errorprone |
+| StaticEJBFieldShouldBeFinal | Static EJBField should be final | Medium | Active | | errorprone |
+| SuspiciousOctalEscape | Suspicious octal escape | Medium | Active | | errorprone |
+| TooManyFields | Too many fields | Medium | Active | | design |
+| TooManyStaticImports | Too many static imports | Medium | Active | | codestyle |
+| UnusedAssignment | Unused assignment | Medium | Active | | bestpractices |
+| UnusedNullCheckInEquals | Unused null check in equals | Medium | Active | | errorprone |
+| UseArraysAsList | Use arrays as list | Medium | Active | | performance |
+| UseConcurrentHashMap | Use concurrent hash map | Medium | Active | | multithreading |
+| UseIndexOfChar | Use index of char | Medium | Active | | performance |
+| UseLocaleWithCaseConversions | Use locale with case conversions | Medium | Active | | errorprone |
+| UseStringBufferForStringAppends | Use string buffer for string appends | Medium | Active | | performance |
+| UselessQualifiedThis | Useless qualified this | Medium | Active | | codestyle |
+
+## Renamed Rules
+The following rules have new names:
+
+| Rule name | New rule name | Category |
+|-----------|---------------|----------|
+| DefaultLabelNotLastInSwitchStmt | DefaultLabelNotLastInSwitch | bestpractices |
+| GuardLogStatementJavaUtil | GuardLogStatement | bestpractices |
+| JUnit4TestShouldUseAfterAnnotation | UnitTestShouldUseAfterAnnotation | bestpractices |
+| JUnit4TestShouldUseBeforeAnnotation | UnitTestShouldUseBeforeAnnotation | bestpractices |
+| JUnit4TestShouldUseTestAnnotation | UnitTestShouldUseTestAnnotation | bestpractices |
+| JUnitAssertionsShouldIncludeMessage | UnitTestAssertionsShouldIncludeMessage | bestpractices |
+| JUnitTestContainsTooManyAsserts | UnitTestContainsTooManyAsserts | bestpractices |
+| JUnitTestsShouldIncludeAssert | UnitTestShouldIncludeAssert | bestpractices |
+| NonCaseLabelInSwitchStatement | NonCaseLabelInSwitch | errorprone |
+| SwitchStmtsShouldHaveDefault | NonExhaustiveSwitch | bestpractices |
+| TooFewBranchesForASwitchStatement | TooFewBranchesForSwitch | performance |
+
+## Removed Rules
+The following rules have been removed in the new version:
+
+| Rule Key | Priority | Status | Category |
+|----------|----------|--------|----------|
+| AvoidConstantsInterface | Medium | Deprecated | bestpractices |
+| CloneMethodMustImplementCloneableWithTypeResolution | Medium | Deprecated | errorprone |
+| LooseCouplingWithTypeResolution | Medium | Deprecated | bestpractices |
+| UnnecessaryParentheses | Low | Deprecated | codestyle |
+
+Report generated on Wed Jul 16 16:21:38 CEST 2025
diff --git a/docs/pmd_release_notes_4.2.0.md b/docs/pmd_release_notes_4.2.0.md
new file mode 100644
index 00000000..ecd87b27
--- /dev/null
+++ b/docs/pmd_release_notes_4.2.0.md
@@ -0,0 +1,342 @@
+# PMD Rules Release Notes for version 4.2.0
+_Do not edit this generated file._
+
+## Summary
+- Total rules in old version (4.1.0): 282
+- Total rules in new version (4.2.0): 292
+- Rules added: 10
+- Rules removed: 0
+- Rules unchanged: 233
+- Rules updated: 49
+- Rules renamed: 10
+
+## Added Rules
+The following rules have been added in the new version:
+
+| Rule Key | Name | Severity | Category |
+|----------|------|----------|----------|
+| CollectionTypeMismatch | Collection type mismatch | Medium | errorprone |
+| DanglingJavadoc | Dangling javadoc | Medium | documentation |
+| ModifierOrder | Modifier order | Medium | codestyle |
+| OverrideBothEqualsAndHashCodeOnComparable | Override both equals and hash code on comparable | Medium | errorprone |
+| RelianceOnDefaultCharset | Reliance on default charset | Medium | bestpractices |
+| ReplaceJavaUtilCalendar | Replace java util calendar | Medium | errorprone |
+| ReplaceJavaUtilDate | Replace java util date | Medium | errorprone |
+| TypeParameterNamingConventions | Type parameter naming conventions | Low | codestyle |
+| UselessPureMethodCall | Useless pure method call | Medium | errorprone |
+| VariableCanBeInlined | Variable can be inlined | Low | codestyle |
+
+## Updated Rules
+The following rules have been updated in the new version:
+
+| Rule Key | Name | Old Severity | New Severity | Old Status | New Status | Alternatives | Category |
+|----------|------|--------------|--------------|------------|------------|--------------|----------|
+| AtLeastOneConstructor | At least one constructor | Medium | Low | | Active | | codestyle |
+| AvoidDollarSigns | Avoid dollar signs | Medium | Low | | Active | | codestyle |
+| AvoidLosingExceptionInformation | Avoid losing exception information | | | Active | Deprecated | | errorprone |
+| AvoidProtectedFieldInFinalClass | Avoid protected field in final class | Medium | Low | | Active | | codestyle |
+| AvoidProtectedMethodInFinalClassNotExtending | Avoid protected method in final class not extending | Medium | Low | | Active | | codestyle |
+| AvoidUsingNativeCode | Avoid using native code | High | Medium | | Active | | codestyle |
+| CallSuperInConstructor | Call super in constructor | Medium | Low | | Active | | codestyle |
+| ClassNamingConventions | Class naming conventions | Blocker | Medium | | Active | | codestyle |
+| CommentDefaultAccessModifier | Comment default access modifier | Medium | Low | | Active | | codestyle |
+| ConfusingTernary | Confusing ternary | Medium | Low | | Active | | codestyle |
+| ControlStatementBraces | Control statement braces | Medium | Low | | Active | | codestyle |
+| EmptyControlStatement | Empty control statement | Medium | Low | | Active | | codestyle |
+| EmptyMethodInAbstractClassShouldBeAbstract | Empty method in abstract class should be abstract | Blocker | Medium | | Active | | codestyle |
+| FieldDeclarationsShouldBeAtStartOfClass | Field declarations should be at start of class | Medium | Low | | Active | | codestyle |
+| FieldNamingConventions | Field naming conventions | Blocker | Medium | | Active | | codestyle |
+| FinalParameterInAbstractMethod | Final parameter in abstract method | Blocker | Medium | | Active | | codestyle |
+| ForLoopShouldBeWhileLoop | For loop should be while loop | Medium | Low | | Active | | codestyle |
+| FormalParameterNamingConventions | Formal parameter naming conventions | Blocker | Medium | | Active | | codestyle |
+| GenericsNaming | Generics naming | | | Active | Deprecated | | codestyle |
+| IdenticalCatchBranches | Identical catch branches | Medium | Low | | Active | | codestyle |
+| InvalidLogMessageFormat | Invalid log message format | Info | Low | | Active | | errorprone |
+| LambdaCanBeMethodReference | Lambda can be method reference | Medium | Low | | Active | | codestyle |
+| LinguisticNaming | Linguistic naming | Medium | Low | | Active | | codestyle |
+| LocalVariableCouldBeFinal | Local variable could be final | Medium | Low | | Active | | codestyle |
+| LocalVariableNamingConventions | Local variable naming conventions | Blocker | Medium | | Active | | codestyle |
+| LongVariable | Long variable | Medium | Low | | Active | | codestyle |
+| MethodArgumentCouldBeFinal | Method argument could be final | Medium | Low | | Active | | codestyle |
+| MethodNamingConventions | Method naming conventions | Blocker | Medium | | Active | | codestyle |
+| NoPackage | No package | Medium | Low | | Active | | codestyle |
+| OnlyOneReturn | Only one return | Medium | Low | | Active | | codestyle |
+| PackageCase | Package case | Medium | Low | | Active | | codestyle |
+| PrematureDeclaration | Premature declaration | Medium | Low | | Active | | codestyle |
+| ShortMethodName | Short method name | Medium | Low | | Active | | codestyle |
+| ShortVariable | Short variable | Medium | Low | | Active | | codestyle |
+| TooManyStaticImports | Too many static imports | Medium | Low | | Active | | codestyle |
+| UnnecessaryAnnotationValueElement | Unnecessary annotation value element | Medium | Low | | Active | | codestyle |
+| UnnecessaryBoxing | Unnecessary boxing | Medium | Low | | Active | | codestyle |
+| UnnecessaryCast | Unnecessary cast | Medium | Low | | Active | | codestyle |
+| UnnecessaryConstructor | Unnecessary constructor | Medium | Low | | Active | | codestyle |
+| UnnecessaryLocalBeforeReturn | Unnecessary local before return | Medium | Low | Active | Deprecated | | codestyle |
+| UnnecessaryModifier | Unnecessary modifier | Medium | Low | | Active | | codestyle |
+| UnnecessaryReturn | Unnecessary return | Medium | Low | | Active | | codestyle |
+| UnnecessarySemicolon | Unnecessary semicolon | Medium | Low | | Active | | codestyle |
+| UseDiamondOperator | Use diamond operator | Medium | Low | | Active | | codestyle |
+| UseExplicitTypes | Use explicit types | Medium | Low | | Active | | codestyle |
+| UseShortArrayInitializer | Use short Array initializer | Medium | Low | | Active | | codestyle |
+| UseUnderscoresInNumericLiterals | Use underscores in numeric literals | Medium | Low | | Active | | codestyle |
+| UselessOperationOnImmutable | Useless operation on immutable | | | Active | Deprecated | | errorprone |
+| UselessQualifiedThis | Useless qualified this | Medium | Low | | Active | | codestyle |
+
+## Unchanged Rules
+The following rules exist in both versions with no changes:
+
+| Rule Key | Name | Severity | Status | Alternatives | Category |
+|----------|------|----------|--------|--------------|----------|
+| AbstractClassWithoutAbstractMethod | Abstract class without abstract method | Medium | Active | | bestpractices |
+| AbstractClassWithoutAnyMethod | Abstract class without any method | Blocker | Active | | design |
+| AccessorClassGeneration | Accessor class generation | Medium | Active | | bestpractices |
+| AccessorMethodGeneration | Accessor method generation | Medium | Active | | bestpractices |
+| AddEmptyString | Add empty string | Medium | Active | | performance |
+| AppendCharacterWithChar | Append character with char | Medium | Active | | performance |
+| ArrayIsStoredDirectly | Array is stored directly | Medium | Active | | bestpractices |
+| AssignmentInOperand | Assignment in operand | Medium | Active | | errorprone |
+| AssignmentToNonFinalStatic | Assignment to non final static | Medium | Active | | errorprone |
+| AvoidAccessibilityAlteration | Avoid accessibility alteration | Medium | Active | | errorprone |
+| AvoidArrayLoops | Avoid array loops | Medium | Active | | performance |
+| AvoidAssertAsIdentifier | Avoid assert as identifier | High | Active | | errorprone |
+| AvoidBranchingStatementAsLastInLoop | Avoid branching statement as last in loop | High | Active | | errorprone |
+| AvoidCalendarDateCreation | Avoid calendar date creation | Medium | Active | | performance |
+| AvoidCallingFinalize | Avoid calling finalize | Medium | Active | | errorprone |
+| AvoidCatchingGenericException | Avoid catching generic exception | Medium | Active | | design |
+| AvoidCatchingNPE | Avoid catching NPE | Medium | Active | | errorprone |
+| AvoidCatchingThrowable | Avoid catching Throwable | Medium | Active | | errorprone |
+| AvoidDecimalLiteralsInBigDecimalConstructor | Avoid decimal literals in BigDecimal constructor | Medium | Active | | errorprone |
+| AvoidDeeplyNestedIfStmts | Avoid deeply nested if stmts | Medium | Active | | design |
+| AvoidDuplicateLiterals | Avoid duplicate literals | Medium | Active | | errorprone |
+| AvoidEnumAsIdentifier | Avoid enum as identifier | High | Active | | errorprone |
+| AvoidFieldNameMatchingMethodName | Avoid field name matching method name | Medium | Active | | errorprone |
+| AvoidFieldNameMatchingTypeName | Avoid field name matching type name | Medium | Active | | errorprone |
+| AvoidFileStream | Avoid file stream | Blocker | Active | | performance |
+| AvoidInstanceofChecksInCatchClause | Avoid instanceof checks in catch clause | Medium | Active | | errorprone |
+| AvoidInstantiatingObjectsInLoops | Avoid instantiating objects in loops | Medium | Active | | performance |
+| AvoidLiteralsInIfCondition | Avoid literals in if condition | Medium | Active | | errorprone |
+| AvoidMessageDigestField | Avoid message digest field | Medium | Active | | bestpractices |
+| AvoidMultipleUnaryOperators | Avoid multiple unary operators | High | Active | | errorprone |
+| AvoidPrintStackTrace | Avoid print stack trace | Medium | Active | | bestpractices |
+| AvoidReassigningCatchVariables | Avoid reassigning catch variables | Medium | Active | | bestpractices |
+| AvoidReassigningLoopVariables | Avoid reassigning loop variables | Medium | Active | | bestpractices |
+| AvoidReassigningParameters | Avoid reassigning parameters | High | Active | | bestpractices |
+| AvoidRethrowingException | Avoid rethrowing exception | Medium | Active | | design |
+| AvoidStringBufferField | Avoid StringBuffer field | Medium | Active | | bestpractices |
+| AvoidSynchronizedAtMethodLevel | Avoid synchronized at method level | Medium | Active | | multithreading |
+| AvoidSynchronizedStatement | Avoid synchronized statement | Medium | Active | | multithreading |
+| AvoidThreadGroup | Avoid ThreadGroup | Medium | Active | | multithreading |
+| AvoidThrowingNewInstanceOfSameException | Avoid throwing new instance of same exception | Medium | Active | | design |
+| AvoidThrowingNullPointerException | Avoid throwing NullPointerException | Blocker | Active | | design |
+| AvoidThrowingRawExceptionTypes | Avoid throwing raw exception types | Blocker | Active | | design |
+| AvoidUncheckedExceptionsInSignatures | Avoid unchecked exceptions in signatures | Medium | Active | | design |
+| AvoidUsingHardCodedIP | Avoid using hard coded IP | Medium | Active | | bestpractices |
+| AvoidUsingOctalValues | Avoid using octal values | Medium | Active | | errorprone |
+| AvoidUsingVolatile | Avoid using volatile | High | Active | | multithreading |
+| BigIntegerInstantiation | BigInteger instantiation | Medium | Active | | performance |
+| BooleanGetMethodName | Boolean get method name | Low | Active | | codestyle |
+| BrokenNullCheck | Broken null check | High | Active | | errorprone |
+| CallSuperFirst | Call super first | Medium | Active | | errorprone |
+| CallSuperLast | Call super last | Medium | Active | | errorprone |
+| CheckResultSet | Check result set | Medium | Active | | bestpractices |
+| CheckSkipResult | Check skip result | Medium | Active | | errorprone |
+| ClassCastExceptionWithToArray | ClassCastException with toArray | Medium | Active | | errorprone |
+| ClassWithOnlyPrivateConstructorsShouldBeFinal | Class with only private constructors should be final | Blocker | Active | | design |
+| CloneMethodMustBePublic | Clone method must be public | Medium | Active | | errorprone |
+| CloneMethodMustImplementCloneable | Clone method must implement Cloneable | Medium | Active | | errorprone |
+| CloneMethodReturnTypeMustMatchClassName | Clone method return type must match class name | Medium | Active | | errorprone |
+| CloseResource | Close resource | Medium | Active | | errorprone |
+| CognitiveComplexity | Cognitive complexity | Medium | Active | | design |
+| CollapsibleIfStatements | Collapsible if statements | Medium | Active | | design |
+| CommentContent | Comment content | Medium | Active | | documentation |
+| CommentRequired | Comment required | Medium | Active | | documentation |
+| CommentSize | Comment size | Medium | Active | | documentation |
+| CompareObjectsWithEquals | Compare objects with equals | Medium | Active | | errorprone |
+| ComparisonWithNaN | Comparison with NaN | Medium | Active | | errorprone |
+| ConfusingArgumentToVarargsMethod | Confusing argument to varargs method | Medium | Active | | errorprone |
+| ConsecutiveAppendsShouldReuse | Consecutive appends should reuse | Medium | Active | | performance |
+| ConsecutiveLiteralAppends | Consecutive literal appends | Medium | Active | | performance |
+| ConstantsInInterface | Constants in interface | Medium | Active | | bestpractices |
+| ConstructorCallsOverridableMethod | Constructor calls overridable method | Blocker | Active | | errorprone |
+| CouplingBetweenObjects | Coupling between objects | Medium | Active | | design |
+| CyclomaticComplexity | Cyclomatic complexity | Medium | Active | | design |
+| DataClass | Data class | Medium | Active | | design |
+| DefaultLabelNotLastInSwitch | Default label not last in switch | Medium | Active | | bestpractices |
+| DetachedTestCase | Detached test case | Medium | Active | | errorprone |
+| DoNotCallGarbageCollectionExplicitly | Do not call garbage collection explicitly | High | Active | | errorprone |
+| DoNotExtendJavaLangError | Do not extend java.lang.Error | Medium | Active | | design |
+| DoNotExtendJavaLangThrowable | Do not extend java.lang.Throwable | Medium | Active | | errorprone |
+| DoNotHardCodeSDCard | Do not hard code SDCard | Medium | Active | | errorprone |
+| DoNotTerminateVM | Do not terminate VM | Medium | Active | | errorprone |
+| DoNotThrowExceptionInFinally | Do not throw exception in finally | Low | Active | | errorprone |
+| DoNotUseThreads | Do not use threads | Medium | Active | | multithreading |
+| DontCallThreadRun | Dont call thread run | Low | Active | | multithreading |
+| DontImportSun | Dont import sun | Low | Active | | errorprone |
+| DontUseFloatTypeForLoopIndices | Dont use float type for loop indices | Medium | Active | | errorprone |
+| DoubleBraceInitialization | Double brace initialization | Medium | Active | | bestpractices |
+| DoubleCheckedLocking | Double checked locking | Blocker | Active | | multithreading |
+| EmptyCatchBlock | Empty catch block | Medium | Active | | errorprone |
+| EmptyFinalizer | Empty finalizer | Medium | Active | | errorprone |
+| EqualsNull | Equals null | Blocker | Active | | errorprone |
+| ExceptionAsFlowControl | Exception as flow control | Medium | Active | | design |
+| ExcessiveImports | Excessive imports | Medium | Active | | design |
+| ExcessiveParameterList | Excessive parameter List | Medium | Active | | design |
+| ExcessivePublicCount | Excessive public count | Medium | Active | | design |
+| ExhaustiveSwitchHasDefault | Exhaustive switch has default | Medium | Active | | bestpractices |
+| ExtendsObject | Extends object | Low | Active | | codestyle |
+| FinalFieldCouldBeStatic | Final field could be static | Medium | Active | | design |
+| FinalizeDoesNotCallSuperFinalize | Finalize does not call super finalize | Medium | Active | | errorprone |
+| FinalizeOnlyCallsSuperFinalize | Finalize only calls super finalize | Medium | Active | | errorprone |
+| FinalizeOverloaded | Finalize overloaded | Medium | Active | | errorprone |
+| FinalizeShouldBeProtected | Finalize should be protected | Medium | Active | | errorprone |
+| ForLoopCanBeForeach | For loop can be foreach | Medium | Active | | bestpractices |
+| ForLoopVariableCount | For loop variable count | Medium | Active | | bestpractices |
+| GodClass | God class | Medium | Active | | design |
+| GuardLogStatement | Guard log statement | High | Active | | bestpractices |
+| HardCodedCryptoKey | Hard coded crypto key | Medium | Active | | security |
+| IdempotentOperations | Idempotent operations | Medium | Active | | errorprone |
+| ImmutableField | Immutable field | Medium | Active | | design |
+| ImplicitFunctionalInterface | Implicit functional interface | High | Active | | bestpractices |
+| ImplicitSwitchFallThrough | Implicit switch fall through | Medium | Active | | errorprone |
+| InefficientEmptyStringCheck | Inefficient empty string check | Medium | Active | | performance |
+| InefficientStringBuffering | Inefficient string buffering | Medium | Active | | performance |
+| InsecureCryptoIv | Insecure crypto IV | Medium | Active | | security |
+| InstantiationToGetClass | Instantiation to get class | Low | Active | | errorprone |
+| InsufficientStringBufferDeclaration | Insufficient StringBuffer declaration | Medium | Active | | performance |
+| InvalidJavaBean | Invalid Java bean | Medium | Active | | design |
+| JUnit4SuitesShouldUseSuiteAnnotation | JUnit4 suites should use suite annotation | Medium | Active | | bestpractices |
+| JUnit5TestShouldBePackagePrivate | JUnit5 test should be package private | Medium | Active | | bestpractices |
+| JUnitSpelling | JUnit spelling | Medium | Active | | errorprone |
+| JUnitStaticSuite | JUnit static suite | Medium | Active | | errorprone |
+| JUnitUseExpected | JUnit use expected | Medium | Active | | bestpractices |
+| JumbledIncrementer | Jumbled incrementer | Medium | Active | | errorprone |
+| LawOfDemeter | Law of demeter | Medium | Active | | design |
+| LiteralsFirstInComparisons | Literals first in comparisons | Medium | Active | | bestpractices |
+| LocalHomeNamingConvention | Local home naming convention | Low | Active | | codestyle |
+| LocalInterfaceSessionNamingConvention | Local interface session naming convention | Low | Active | | codestyle |
+| LogicInversion | Logic inversion | Medium | Active | | design |
+| LooseCoupling | Loose coupling | Medium | Active | | bestpractices |
+| LoosePackageCoupling | Loose package coupling | Medium | Active | | design |
+| MDBAndSessionBeanNamingConvention | MDB and session bean naming convention | Low | Active | | codestyle |
+| MethodReturnsInternalArray | Method returns internal array | Medium | Active | | bestpractices |
+| MethodWithSameNameAsEnclosingClass | Method with same name as enclosing class | Medium | Active | | errorprone |
+| MisplacedNullCheck | Misplaced null check | Medium | Active | | errorprone |
+| MissingOverride | Missing override | Medium | Active | | bestpractices |
+| MissingSerialVersionUID | Missing serialVersionUID | Medium | Active | | errorprone |
+| MissingStaticMethodInNonInstantiatableClass | Missing static method in non instantiatable class | Medium | Active | | errorprone |
+| MoreThanOneLogger | More than one logger | High | Active | | errorprone |
+| MutableStaticState | Mutable static state | Medium | Active | | design |
+| NPathComplexity | NPath complexity | Medium | Active | | design |
+| NcssCount | NCSS count | Medium | Active | | design |
+| NonCaseLabelInSwitch | Non case label in switch | Medium | Active | | errorprone |
+| NonExhaustiveSwitch | Non exhaustive switch | Medium | Active | | bestpractices |
+| NonSerializableClass | Non serializable class | Medium | Active | | errorprone |
+| NonStaticInitializer | Non static initializer | Medium | Active | | errorprone |
+| NonThreadSafeSingleton | Non thread safe singleton | Medium | Active | | multithreading |
+| NullAssignment | Null assignment | Medium | Active | | errorprone |
+| OneDeclarationPerLine | One declaration per line | Low | Active | | bestpractices |
+| OptimizableToArrayCall | Optimizable toArray call | Medium | Active | | performance |
+| OverrideBothEqualsAndHashcode | Override both equals and hashcode | Medium | Active | | errorprone |
+| PreserveStackTrace | Preserve stack trace | Medium | Active | | bestpractices |
+| PrimitiveWrapperInstantiation | Primitive wrapper instantiation | Medium | Active | | bestpractices |
+| ProperCloneImplementation | Proper clone implementation | High | Active | | errorprone |
+| ProperLogger | Proper logger | Medium | Active | | errorprone |
+| RedundantFieldInitializer | Redundant field initializer | Medium | Active | | performance |
+| RemoteInterfaceNamingConvention | Remote interface naming convention | Low | Active | | codestyle |
+| RemoteSessionInterfaceNamingConvention | Remote session interface naming convention | Low | Active | | codestyle |
+| ReplaceEnumerationWithIterator | Replace Enumeration with Iterator | Medium | Active | | bestpractices |
+| ReplaceHashtableWithMap | Replace Hashtable with Map | Medium | Active | | bestpractices |
+| ReplaceVectorWithList | Replace Vector with List | Medium | Active | | bestpractices |
+| ReturnEmptyCollectionRatherThanNull | Return empty collection rather than null | Blocker | Active | | errorprone |
+| ReturnFromFinallyBlock | Return from finally block | Medium | Active | | errorprone |
+| ShortClassName | Short class name | Low | Active | | codestyle |
+| SignatureDeclareThrowsException | Signature declare throws Exception | Medium | Active | | design |
+| SimpleDateFormatNeedsLocale | SimpleDateFormat needs Locale | Medium | Active | | errorprone |
+| SimplifiableTestAssertion | Simplifiable test assertion | Medium | Active | | bestpractices |
+| SimplifiedTernary | Simplified ternary | Medium | Active | | design |
+| SimplifyBooleanExpressions | Simplify boolean expressions | Medium | Active | | design |
+| SimplifyBooleanReturns | Simplify boolean returns | Medium | Active | | design |
+| SimplifyConditional | Simplify conditional | Medium | Active | | design |
+| SingleMethodSingleton | Single method singleton | High | Active | | errorprone |
+| SingletonClassReturningNewInstance | Singleton class returning new instance | High | Active | | errorprone |
+| SingularField | Singular field | Medium | Active | | design |
+| StaticEJBFieldShouldBeFinal | Static EJBField should be final | Medium | Active | | errorprone |
+| StringBufferInstantiationWithChar | StringBuffer instantiation with char | Low | Active | | errorprone |
+| StringInstantiation | String instantiation | High | Active | | performance |
+| StringToString | String to string | Medium | Active | | performance |
+| SuspiciousEqualsMethodName | Suspicious equals method name | High | Active | | errorprone |
+| SuspiciousHashcodeMethodName | Suspicious hashcode method name | Medium | Active | | errorprone |
+| SuspiciousOctalEscape | Suspicious octal escape | Medium | Active | | errorprone |
+| SwitchDensity | Switch density | Medium | Active | | design |
+| SystemPrintln | System println | High | Active | | bestpractices |
+| TestClassWithoutTestCases | Test class without test cases | Medium | Active | | errorprone |
+| TooFewBranchesForSwitch | Too few branches for switch | Medium | Active | | performance |
+| TooManyFields | Too many fields | Medium | Active | | design |
+| TooManyMethods | Too many methods | Medium | Active | | design |
+| UncommentedEmptyConstructor | Uncommented empty constructor | Medium | Active | | documentation |
+| UncommentedEmptyMethodBody | Uncommented empty method body | Medium | Active | | documentation |
+| UnconditionalIfStatement | Unconditional if statement | Medium | Active | | errorprone |
+| UnitTestAssertionsShouldIncludeMessage | Unit test assertions should include message | Medium | Active | | bestpractices |
+| UnitTestContainsTooManyAsserts | Unit test contains too many asserts | Medium | Active | | bestpractices |
+| UnitTestShouldIncludeAssert | Unit test should include assert | Medium | Active | | bestpractices |
+| UnitTestShouldUseAfterAnnotation | Unit test should use after annotation | Medium | Active | | bestpractices |
+| UnitTestShouldUseBeforeAnnotation | Unit test should use before annotation | Medium | Active | | bestpractices |
+| UnitTestShouldUseTestAnnotation | Unit test should use test annotation | Medium | Active | | bestpractices |
+| UnnecessaryBooleanAssertion | Unnecessary boolean assertion | Medium | Active | | errorprone |
+| UnnecessaryCaseChange | Unnecessary case change | Medium | Active | | errorprone |
+| UnnecessaryConversionTemporary | Unnecessary conversion temporary | Medium | Active | | errorprone |
+| UnnecessaryFullyQualifiedName | Unnecessary fully qualified name | Low | Active | | codestyle |
+| UnnecessaryImport | Unnecessary import | Low | Active | | codestyle |
+| UnnecessaryVarargsArrayCreation | Unnecessary varargs array creation | Medium | Active | | bestpractices |
+| UnnecessaryWarningSuppression | Unnecessary warning suppression | Medium | Active | | bestpractices |
+| UnsynchronizedStaticFormatter | Unsynchronized static formatter | Medium | Active | | multithreading |
+| UnusedAssignment | Unused assignment | Medium | Active | | bestpractices |
+| UnusedFormalParameter | Unused formal parameter | Medium | Active | | bestpractices |
+| UnusedLocalVariable | Unused local variable | Medium | Active | | bestpractices |
+| UnusedNullCheckInEquals | Unused null check in equals | Medium | Active | | errorprone |
+| UnusedPrivateField | Unused private field | Medium | Active | | bestpractices |
+| UnusedPrivateMethod | Unused private method | Medium | Active | | bestpractices |
+| UseArrayListInsteadOfVector | Use Arrays.asList | Medium | Active | | performance |
+| UseArraysAsList | Use arrays as List | Medium | Active | | performance |
+| UseCollectionIsEmpty | Use Collection.isEmpty | Medium | Active | | bestpractices |
+| UseConcurrentHashMap | Use ConcurrentHashMap | Medium | Active | | multithreading |
+| UseCorrectExceptionLogging | Use correct exception logging | Medium | Active | | errorprone |
+| UseEnumCollections | Use enum collections | Medium | Active | | bestpractices |
+| UseEqualsToCompareStrings | Use equals to compare strings | Medium | Active | | errorprone |
+| UseIOStreamsWithApacheCommonsFileItem | Use IOStreams with apache commons FileItem | Medium | Active | | performance |
+| UseIndexOfChar | Use index of char | Medium | Active | | performance |
+| UseLocaleWithCaseConversions | Use Locale with case conversions | Medium | Active | | errorprone |
+| UseNotifyAllInsteadOfNotify | Use notifyAll instead of notify | Medium | Active | | multithreading |
+| UseObjectForClearerAPI | Use object for clearer API | Medium | Active | | design |
+| UseProperClassLoader | Use proper ClassLoader | Medium | Active | | errorprone |
+| UseStandardCharsets | Use standard Charsets | Medium | Active | | bestpractices |
+| UseStringBufferForStringAppends | Use StringBuffer for string appends | Medium | Active | | performance |
+| UseStringBufferLength | Use StringBuffer length | Medium | Active | | performance |
+| UseTryWithResources | Use try with resources | Medium | Active | | bestpractices |
+| UseUtilityClass | Use utility class | Medium | Active | | design |
+| UseVarargs | Use varargs | Low | Active | | bestpractices |
+| UselessOverridingMethod | Useless overriding method | Medium | Active | | design |
+| UselessParentheses | Useless parentheses | Low | Active | | codestyle |
+| UselessStringValueOf | Useless String.valueOf | Medium | Active | | performance |
+| WhileLoopWithLiteralBoolean | While loop with literal boolean | Medium | Active | | bestpractices |
+| XPathRule | PMD XPath Template Rule | | Active | | |
+
+## Renamed Rules
+The following rules have new names:
+
+| Rule name | New rule name | Category |
+|-----------|---------------|----------|
+| DefaultLabelNotLastInSwitchStmt | DefaultLabelNotLastInSwitch | bestpractices |
+| JUnit4TestShouldUseAfterAnnotation | UnitTestShouldUseAfterAnnotation | bestpractices |
+| JUnit4TestShouldUseBeforeAnnotation | UnitTestShouldUseBeforeAnnotation | bestpractices |
+| JUnit4TestShouldUseTestAnnotation | UnitTestShouldUseTestAnnotation | bestpractices |
+| JUnitAssertionsShouldIncludeMessage | UnitTestAssertionsShouldIncludeMessage | bestpractices |
+| JUnitTestContainsTooManyAsserts | UnitTestContainsTooManyAsserts | bestpractices |
+| JUnitTestsShouldIncludeAssert | UnitTestShouldIncludeAssert | bestpractices |
+| NonCaseLabelInSwitchStatement | NonCaseLabelInSwitch | errorprone |
+| SwitchStmtsShouldHaveDefault | NonExhaustiveSwitch | bestpractices |
+| TooFewBranchesForASwitchStatement | TooFewBranchesForSwitch | performance |
+
+## Removed Rules
+No rules were removed.
+
+Report generated on Mon Sep 29 11:44:31 CEST 2025
diff --git a/docs/rules/AbstractClassWithoutAbstractMethod.md b/docs/rules/AbstractClassWithoutAbstractMethod.md
deleted file mode 100644
index 0feda2db..00000000
--- a/docs/rules/AbstractClassWithoutAbstractMethod.md
+++ /dev/null
@@ -1,9 +0,0 @@
-# AbstractClassWithoutAbstractMethod
-**Category:** `pmd`
-**Rule Key:** `pmd:AbstractClassWithoutAbstractMethod`
-> :warning: This rule is **deprecated** in favour of [S1694](https://rules.sonarsource.com/java/RSPEC-1694).
-
------
-
-
-The abstract class does not contain any abstract methods. An abstract class suggests an incomplete implementation, which is to be completed by subclasses implementing the abstract methods. If the class is intended to be used as a base class only (not to be instantiated directly) a protected constructor can be provided prevent direct instantiation.
diff --git a/docs/rules/AbstractClassWithoutAnyMethod.md b/docs/rules/AbstractClassWithoutAnyMethod.md
deleted file mode 100644
index feb03186..00000000
--- a/docs/rules/AbstractClassWithoutAnyMethod.md
+++ /dev/null
@@ -1,16 +0,0 @@
-# AbstractClassWithoutAnyMethod
-**Category:** `pmd`
-**Rule Key:** `pmd:AbstractClassWithoutAnyMethod`
-> :warning: This rule is **deprecated** in favour of [S1694](https://rules.sonarsource.com/java/RSPEC-1694).
-
------
-
-
-If an abstract class does not provide any method, it may be acting as a simple data container that is not meant to be instantiated. In this case, it is probably better to use a private or protected constructor in order to prevent instantiation than make the class misleadingly abstract.
-Example:
-
-public class abstract Example {
- String field;
- int otherField;
-}
-
diff --git a/docs/rules/AbstractNaming.md b/docs/rules/AbstractNaming.md
deleted file mode 100644
index 30aed19d..00000000
--- a/docs/rules/AbstractNaming.md
+++ /dev/null
@@ -1,14 +0,0 @@
-# AbstractNaming
-**Category:** `pmd`
-**Rule Key:** `pmd:AbstractNaming`
-> :warning: This rule is **deprecated** in favour of [S00118](https://rules.sonarsource.com/java/RSPEC-118).
-
------
-
-
-Abstract classes should be named 'AbstractXXX'.
-Example:
h2>
-
-public abstract class Foo { // should be AbstractFoo
-}
-
diff --git a/docs/rules/AccessorClassGeneration.md b/docs/rules/AccessorClassGeneration.md
deleted file mode 100644
index 9a9d7568..00000000
--- a/docs/rules/AccessorClassGeneration.md
+++ /dev/null
@@ -1,25 +0,0 @@
-# AccessorClassGeneration
-**Category:** `pmd`
-**Rule Key:** `pmd:AccessorClassGeneration`
-
-
------
-
-
-Instantiation by way of private constructors from outside of the constructor’s class often causes the generation of an accessor.
-A factory method, or non-privatization of the constructor can eliminate this situation.
-The generated class file is actually an interface. It gives the accessing class the ability to invoke a new hidden package scope constructor that takes the interface as a supplementary parameter.
-This turns a private constructor effectively into one with package scope, and is challenging to discern.
-
-Example:
-
-public class Outer {
- void method() {
- Inner ic = new Inner(); // Causes generation of accessor class
- }
-
- public class Inner {
- private Inner() {}
- }
-}
-
diff --git a/docs/rules/AddEmptyString.md b/docs/rules/AddEmptyString.md
deleted file mode 100644
index 189c61d5..00000000
--- a/docs/rules/AddEmptyString.md
+++ /dev/null
@@ -1,16 +0,0 @@
-# AddEmptyString
-**Category:** `pmd`
-**Rule Key:** `pmd:AddEmptyString`
-
-
------
-
-
-The conversion of literals to strings by concatenating them with empty strings is inefficient.
-It is much better to use one of the type-specific toString() methods instead.
-
-Example:
-
-String s = "" + 123; // inefficient
-String t = Integer.toString(456); // preferred approach
-
diff --git a/docs/rules/AppendCharacterWithChar.md b/docs/rules/AppendCharacterWithChar.md
deleted file mode 100644
index a10c3d35..00000000
--- a/docs/rules/AppendCharacterWithChar.md
+++ /dev/null
@@ -1,20 +0,0 @@
-# AppendCharacterWithChar
-**Category:** `pmd`
-**Rule Key:** `pmd:AppendCharacterWithChar`
-
-
------
-
-
-Avoid concatenating characters as strings in StringBuffer
/StringBuilder.append
methods.
-
-Noncompliant Code Example
-
-StringBuffer sb = new StringBuffer();
-sb.append("a"); // avoid this
-
-Compliant Solution
-
-StringBuffer sb = new StringBuffer();
-sb.append('a'); // use this instead
-
diff --git a/docs/rules/ArrayIsStoredDirectly.md b/docs/rules/ArrayIsStoredDirectly.md
deleted file mode 100644
index b2934303..00000000
--- a/docs/rules/ArrayIsStoredDirectly.md
+++ /dev/null
@@ -1,9 +0,0 @@
-# ArrayIsStoredDirectly
-**Category:** `pmd`
-**Rule Key:** `pmd:ArrayIsStoredDirectly`
-> :warning: This rule is **deprecated** in favour of [S2384](https://rules.sonarsource.com/java/RSPEC-2384).
-
------
-
-
-Constructors and methods receiving arrays should clone objects and store the copy. This prevents future changes from the user from affecting the original array.
diff --git a/docs/rules/AssignmentInOperand.md b/docs/rules/AssignmentInOperand.md
deleted file mode 100644
index baad8c4f..00000000
--- a/docs/rules/AssignmentInOperand.md
+++ /dev/null
@@ -1,19 +0,0 @@
-# AssignmentInOperand
-**Category:** `pmd`
-**Rule Key:** `pmd:AssignmentInOperand`
-> :warning: This rule is **deprecated** in favour of `squid:AssignmentInSubExpressionCheck`.
-
------
-
-
-Avoid assignments in operands; this can make code more complicated and harder to read.
-
-Example:
-
-public void bar() {
- int x = 2;
- if ((x = getX()) == 3) {
- System.out.println("3!");
- }
-}
-
diff --git a/docs/rules/AssignmentToNonFinalStatic.md b/docs/rules/AssignmentToNonFinalStatic.md
deleted file mode 100644
index 7cb9f286..00000000
--- a/docs/rules/AssignmentToNonFinalStatic.md
+++ /dev/null
@@ -1,19 +0,0 @@
-# AssignmentToNonFinalStatic
-**Category:** `pmd`
-**Rule Key:** `pmd:AssignmentToNonFinalStatic`
-
-
------
-
-
-Identifies a possible unsafe usage of a static field.
-
-Example:
-
-public class StaticField {
- static int x;
- public FinalFields(int y) {
- x = y; // unsafe
- }
-}
-
diff --git a/docs/rules/AtLeastOneConstructor.md b/docs/rules/AtLeastOneConstructor.md
deleted file mode 100644
index b6b0e181..00000000
--- a/docs/rules/AtLeastOneConstructor.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# AtLeastOneConstructor
-**Category:** `pmd`
-**Rule Key:** `pmd:AtLeastOneConstructor`
-> :warning: This rule is **deprecated** in favour of [S1118](https://rules.sonarsource.com/java/RSPEC-1118), [S1258](https://rules.sonarsource.com/java/RSPEC-1258).
-
------
-
-Each non-static class should declare at least one constructor. Classes with solely static members ("Utility class") are ignored.
diff --git a/docs/rules/AvoidAccessibilityAlteration.md b/docs/rules/AvoidAccessibilityAlteration.md
deleted file mode 100644
index 3b572dec..00000000
--- a/docs/rules/AvoidAccessibilityAlteration.md
+++ /dev/null
@@ -1,42 +0,0 @@
-# AvoidAccessibilityAlteration
-**Category:** `pmd`
-**Rule Key:** `pmd:AvoidAccessibilityAlteration`
-
-
------
-
-
-Methods such as getDeclaredConstructors(), getDeclaredConstructor(Class[]) and setAccessible(), as the interface PrivilegedAction, allow for the runtime alteration of variable, class, or method visibility, even if they are private. This violates the principle of encapsulation.
-
-Example:
-
-import java.lang.reflect.AccessibleObject;
-import java.lang.reflect.Method;
-import java.security.PrivilegedAction;
-
-public class Violation {
- public void invalidCallsInMethod() throws SecurityException, NoSuchMethodException {
-
- // Possible call to forbidden getDeclaredConstructors
- Class[] arrayOfClass = new Class[1];
- this.getClass().getDeclaredConstructors();
- this.getClass().getDeclaredConstructor(arrayOfClass);
- Class clazz = this.getClass();
- clazz.getDeclaredConstructor(arrayOfClass);
- clazz.getDeclaredConstructors();
-
- // Possible call to forbidden setAccessible
- clazz.getMethod("", arrayOfClass).setAccessible(false);
- AccessibleObject.setAccessible(null, false);
- Method.setAccessible(null, false);
- Method[] methodsArray = clazz.getMethods();
- int nbMethod;
- for (nbMethod = 0; nbMethod < methodsArray.length; nbMethod++ ) {
- methodsArray[nbMethod].setAccessible(false);
- }
-
- // Possible call to forbidden PrivilegedAction
- PrivilegedAction priv = (PrivilegedAction) new Object(); priv.run();
- }
-}
-
diff --git a/docs/rules/AvoidArrayLoops.md b/docs/rules/AvoidArrayLoops.md
deleted file mode 100644
index 948d5f53..00000000
--- a/docs/rules/AvoidArrayLoops.md
+++ /dev/null
@@ -1,31 +0,0 @@
-# AvoidArrayLoops
-**Category:** `pmd`
-**Rule Key:** `pmd:AvoidArrayLoops`
-
-
------
-
-
-Instead of manually copying data between two arrays, use the efficient Arrays.copyOf or System.arraycopy method instead.
-
-Noncompliant Code Example
-
-int[] a = new int[10];
-int[] b = new int[10];
-
-for (int i = 0; i < 10; i++) {
- b[i] = a[i];
-}
-
-
-Compliant Solution
-
-int[] a = new int[10];
-int[] b;
-
-// Option 1
-b = Arrays.copyOf(a, a.length);
-
-// Option 2
-System.arraycopy(a, 0, b, 0, a.length);
-
diff --git a/docs/rules/AvoidAssertAsIdentifier.md b/docs/rules/AvoidAssertAsIdentifier.md
deleted file mode 100644
index b0211a50..00000000
--- a/docs/rules/AvoidAssertAsIdentifier.md
+++ /dev/null
@@ -1,9 +0,0 @@
-# AvoidAssertAsIdentifier
-**Category:** `pmd`
-**Rule Key:** `pmd:AvoidAssertAsIdentifier`
-> :warning: This rule is **deprecated** in favour of [S1190](https://rules.sonarsource.com/java/RSPEC-1190).
-
------
-
-
-Use of the term assert
will conflict with newer versions of Java since it is a reserved word.
diff --git a/docs/rules/AvoidBranchingStatementAsLastInLoop.md b/docs/rules/AvoidBranchingStatementAsLastInLoop.md
deleted file mode 100644
index b5a15790..00000000
--- a/docs/rules/AvoidBranchingStatementAsLastInLoop.md
+++ /dev/null
@@ -1,30 +0,0 @@
-# AvoidBranchingStatementAsLastInLoop
-**Category:** `pmd`
-**Rule Key:** `pmd:AvoidBranchingStatementAsLastInLoop`
-
-
------
-
-
-Using a branching statement as the last part of a loop may be a bug, and/or is confusing. Ensure that the usage is not a bug, or consider using another approach.
-
-Noncompliant Code Example
-
-// unusual use of branching statement in a loop
-for (int i = 0; i < 10; i++) {
- if (i*i <= 25) {
- continue;
- }
- break;
-}
-
-
-Compliant Solution
-
-// this makes more sense...
-for (int i = 0; i < 10; i++) {
- if (i*i > 25) {
- break;
- }
-}
-
diff --git a/docs/rules/AvoidCallingFinalize.md b/docs/rules/AvoidCallingFinalize.md
deleted file mode 100644
index 37db4274..00000000
--- a/docs/rules/AvoidCallingFinalize.md
+++ /dev/null
@@ -1,15 +0,0 @@
-# AvoidCallingFinalize
-**Category:** `pmd`
-**Rule Key:** `pmd:AvoidCallingFinalize`
-> :warning: This rule is **deprecated** in favour of `squid:ObjectFinalizeCheck`.
-
------
-
-
-Object.finalize()
is called by the garbage collector on an object when garbage collection determines that there are no more references to the object.
- It should not be invoked by application logic.
-Object.finalize()
as deprecated since JDK 9.
-
-**Rule Key:** `pmd:AvoidCatchingGenericException`
-> :warning: This rule is **deprecated** in favour of [S2221](https://rules.sonarsource.com/java/RSPEC-2221).
-
------
-
-
-Avoid catching generic exceptions such as NullPointerException, RuntimeException, Exception in try-catch block.
diff --git a/docs/rules/AvoidCatchingNPE.md b/docs/rules/AvoidCatchingNPE.md
deleted file mode 100644
index acd8f61c..00000000
--- a/docs/rules/AvoidCatchingNPE.md
+++ /dev/null
@@ -1,10 +0,0 @@
-# AvoidCatchingNPE
-**Category:** `pmd`
-**Rule Key:** `pmd:AvoidCatchingNPE`
-> :warning: This rule is **deprecated** in favour of [S1696](https://rules.sonarsource.com/java/RSPEC-1696).
-
------
-
-
-Code should never throw NullPointerException
s under normal circumstances.
-A catch block may hide the original error, causing other, more subtle problems later on.
diff --git a/docs/rules/AvoidCatchingThrowable.md b/docs/rules/AvoidCatchingThrowable.md
deleted file mode 100644
index 47dabc4f..00000000
--- a/docs/rules/AvoidCatchingThrowable.md
+++ /dev/null
@@ -1,10 +0,0 @@
-# AvoidCatchingThrowable
-**Category:** `pmd`
-**Rule Key:** `pmd:AvoidCatchingThrowable`
-> :warning: This rule is **deprecated** in favour of [S1181](https://rules.sonarsource.com/java/RSPEC-1181).
-
------
-
-
-Catching Throwable
errors is not recommended since its scope is very broad. It includes runtime issues such as
-OutOfMemoryError
that should be exposed and managed separately.
diff --git a/docs/rules/AvoidConstantsInterface.md b/docs/rules/AvoidConstantsInterface.md
deleted file mode 100644
index 5739fc77..00000000
--- a/docs/rules/AvoidConstantsInterface.md
+++ /dev/null
@@ -1,15 +0,0 @@
-# AvoidConstantsInterface
-**Category:** `pmd`
-**Rule Key:** `pmd:AvoidConstantsInterface`
-> :warning: This rule is **deprecated** in favour of [S1214](https://rules.sonarsource.com/java/RSPEC-1214).
-
------
-
-
-
-**Rule Key:** `pmd:AvoidDecimalLiteralsInBigDecimalConstructor`
-> :warning: This rule is **deprecated** in favour of [S2111](https://rules.sonarsource.com/java/RSPEC-2111).
-
------
-
-
-new BigDecimal(0.1)
is exactly equal to 0.1
, but it is
- actually equal to .1000000000000000055511151231257827021181583404541015625
. This is because 0.1
- cannot be represented exactly as a double (or as a binary fraction of any finite length).
- Thus, the long value that is being passed in to the constructor is not exactly equal to 0.1, appearances notwithstanding.
-new BigDecimal("0.1")
is exactly equal
- to 0.1
, as one would expect. Therefore, it is generally recommended that the (String) constructor be used in preference to this one.
-Noncompliant Code Example
-
-BigDecimal bd = new BigDecimal(1.123); // loss of precision, this would trigger the rule
-
-
-Compliant Solution
-
-BigDecimal bd = new BigDecimal("1.123"); // preferred approach
-
-BigDecimal bd = new BigDecimal(12); // preferred approach, ok for integer values
-
diff --git a/docs/rules/AvoidDeeplyNestedIfStmts.md b/docs/rules/AvoidDeeplyNestedIfStmts.md
deleted file mode 100644
index 928d00d8..00000000
--- a/docs/rules/AvoidDeeplyNestedIfStmts.md
+++ /dev/null
@@ -1,9 +0,0 @@
-# AvoidDeeplyNestedIfStmts
-**Category:** `pmd`
-**Rule Key:** `pmd:AvoidDeeplyNestedIfStmts`
-> :warning: This rule is **deprecated** in favour of [S134](https://rules.sonarsource.com/java/RSPEC-134).
-
------
-
-
-Avoid creating deeply nested if-then statements since they are harder to read and error-prone to maintain.
diff --git a/docs/rules/AvoidDollarSigns.md b/docs/rules/AvoidDollarSigns.md
deleted file mode 100644
index 268f0250..00000000
--- a/docs/rules/AvoidDollarSigns.md
+++ /dev/null
@@ -1,15 +0,0 @@
-# AvoidDollarSigns
-**Category:** `pmd`
-**Rule Key:** `pmd:AvoidDollarSigns`
-> :warning: This rule is **deprecated** in favour of [S00114](https://rules.sonarsource.com/java/RSPEC-114), [S00115](https://rules.sonarsource.com/java/RSPEC-115), [S00116](https://rules.sonarsource.com/java/RSPEC-116), [S00117](https://rules.sonarsource.com/java/RSPEC-117).
-
------
-
-
-**Rule Key:** `pmd:AvoidDuplicateLiterals`
-> :warning: This rule is **deprecated** in favour of [S1192](https://rules.sonarsource.com/java/RSPEC-1192).
-
------
-
-Code containing duplicate String literals can usually be improved by declaring the String as a constant field. Example :
-
-public class Foo {
- private void bar() {
- buz("Howdy");
- buz("Howdy");
- buz("Howdy");
- buz("Howdy");
- }
- private void buz(String x) {}
-}
-
diff --git a/docs/rules/AvoidEnumAsIdentifier.md b/docs/rules/AvoidEnumAsIdentifier.md
deleted file mode 100644
index 7d42b824..00000000
--- a/docs/rules/AvoidEnumAsIdentifier.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# AvoidEnumAsIdentifier
-**Category:** `pmd`
-**Rule Key:** `pmd:AvoidEnumAsIdentifier`
-> :warning: This rule is **deprecated** in favour of [S1190](https://rules.sonarsource.com/java/RSPEC-1190).
-
------
-
-Finds all places 'enum' is used as an identifier is used.
diff --git a/docs/rules/AvoidFieldNameMatchingMethodName.md b/docs/rules/AvoidFieldNameMatchingMethodName.md
deleted file mode 100644
index 1fdcc8b8..00000000
--- a/docs/rules/AvoidFieldNameMatchingMethodName.md
+++ /dev/null
@@ -1,16 +0,0 @@
-# AvoidFieldNameMatchingMethodName
-**Category:** `pmd`
-**Rule Key:** `pmd:AvoidFieldNameMatchingMethodName`
-> :warning: This rule is **deprecated** in favour of [S1845](https://rules.sonarsource.com/java/RSPEC-1845).
-
------
-
-It is somewhat confusing to have a field name with the same name as a method. While this is totally legal, having information (field) and actions (method) is not clear naming. Example :
-
-public class Foo {
- Object bar;
- // bar is data or an action or both?
- void bar() {
- }
-}
-
diff --git a/docs/rules/AvoidFieldNameMatchingTypeName.md b/docs/rules/AvoidFieldNameMatchingTypeName.md
deleted file mode 100644
index 1d654751..00000000
--- a/docs/rules/AvoidFieldNameMatchingTypeName.md
+++ /dev/null
@@ -1,14 +0,0 @@
-# AvoidFieldNameMatchingTypeName
-**Category:** `pmd`
-**Rule Key:** `pmd:AvoidFieldNameMatchingTypeName`
-> :warning: This rule is **deprecated** in favour of [S1700](https://rules.sonarsource.com/java/RSPEC-1700).
-
------
-
-It is somewhat confusing to have a field name matching the declaring class name. This probably means that type and or field names could be more precise. Example :
-
-public class Foo extends Bar {
- // There's probably a better name for foo
- int foo;
-}
-
diff --git a/docs/rules/AvoidFinalLocalVariable.md b/docs/rules/AvoidFinalLocalVariable.md
deleted file mode 100644
index 4b19f892..00000000
--- a/docs/rules/AvoidFinalLocalVariable.md
+++ /dev/null
@@ -1,15 +0,0 @@
-# AvoidFinalLocalVariable
-**Category:** `pmd`
-**Rule Key:** `pmd:AvoidFinalLocalVariable`
-
-
------
-
-Avoid using final local variables, turn them into fields. Example :
-
-public class MyClass {
- public void foo() {
- final String finalLocalVariable;
- }
-}
-
diff --git a/docs/rules/AvoidInstanceofChecksInCatchClause.md b/docs/rules/AvoidInstanceofChecksInCatchClause.md
deleted file mode 100644
index 989f9a33..00000000
--- a/docs/rules/AvoidInstanceofChecksInCatchClause.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# AvoidInstanceofChecksInCatchClause
-**Category:** `pmd`
-**Rule Key:** `pmd:AvoidInstanceofChecksInCatchClause`
-> :warning: This rule is **deprecated** in favour of [S1193](https://rules.sonarsource.com/java/RSPEC-1193).
-
------
-
-Each caught exception type should be handled in its own catch clause.
diff --git a/docs/rules/AvoidInstantiatingObjectsInLoops.md b/docs/rules/AvoidInstantiatingObjectsInLoops.md
deleted file mode 100644
index 78c666a7..00000000
--- a/docs/rules/AvoidInstantiatingObjectsInLoops.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# AvoidInstantiatingObjectsInLoops
-**Category:** `pmd`
-**Rule Key:** `pmd:AvoidInstantiatingObjectsInLoops`
-
-
------
-
-Detects when a new object is created inside a loop
diff --git a/docs/rules/AvoidLiteralsInIfCondition.md b/docs/rules/AvoidLiteralsInIfCondition.md
deleted file mode 100644
index cfca6964..00000000
--- a/docs/rules/AvoidLiteralsInIfCondition.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# AvoidLiteralsInIfCondition
-**Category:** `pmd`
-**Rule Key:** `pmd:AvoidLiteralsInIfCondition`
-> :warning: This rule is **deprecated** in favour of [S109](https://rules.sonarsource.com/java/RSPEC-109).
-
------
-
-Avoid using hard coded literals in conditional statements, declare those as static variables or private members.
diff --git a/docs/rules/AvoidLosingExceptionInformation.md b/docs/rules/AvoidLosingExceptionInformation.md
deleted file mode 100644
index f1e01d9b..00000000
--- a/docs/rules/AvoidLosingExceptionInformation.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# AvoidLosingExceptionInformation
-**Category:** `pmd`
-**Rule Key:** `pmd:AvoidLosingExceptionInformation`
-> :warning: This rule is **deprecated** in favour of [S1166](https://rules.sonarsource.com/java/RSPEC-1166).
-
------
-
-Statements in a catch block that invoke accessors on the exception without using the information only add to code size. Either remove the invocation, or use the return result.
diff --git a/docs/rules/AvoidMultipleUnaryOperators.md b/docs/rules/AvoidMultipleUnaryOperators.md
deleted file mode 100644
index 7529a30b..00000000
--- a/docs/rules/AvoidMultipleUnaryOperators.md
+++ /dev/null
@@ -1,27 +0,0 @@
-# AvoidMultipleUnaryOperators
-**Category:** `pmd`
-**Rule Key:** `pmd:AvoidMultipleUnaryOperators`
-> :warning: This rule is **deprecated** in favour of [S881](https://rules.sonarsource.com/java/RSPEC-881).
-
------
-
-Using multiple unary operators may be a bug, and/or is confusing. Check the usage is not a bug, or consider simplifying the expression. Example :
-
-// These are typo bugs, or at best needlessly complex and confusing:
-int i = - -1;
-int j = + - +1;
-int z = ~~2;
-boolean b = !!true;
-boolean c = !!!true;
-
-// These are better:
-int i = 1;
-int j = -1;
-int z = 2;
-boolean b = true;
-boolean c = false;
-
-// And these just make your brain hurt:
-int i = ~-2;
-int j = -~7;
-
diff --git a/docs/rules/AvoidPrefixingMethodParameters.md b/docs/rules/AvoidPrefixingMethodParameters.md
deleted file mode 100644
index 076b707c..00000000
--- a/docs/rules/AvoidPrefixingMethodParameters.md
+++ /dev/null
@@ -1,20 +0,0 @@
-# AvoidPrefixingMethodParameters
-**Category:** `pmd`
-**Rule Key:** `pmd:AvoidPrefixingMethodParameters`
-> :warning: This rule is **deprecated** in favour of [S00117](https://rules.sonarsource.com/java/RSPEC-117).
-
------
-
-Prefixing parameters by 'in' or 'out' pollutes the name of the parameters and reduces code readability.
-To indicate whether or not a parameter will be modify in a method, its better to document method
-behavior with Javadoc. Example:
-
-// Not really clear
-public class Foo {
- public void bar(
- int inLeftOperand,
- Result outRightOperand) {
- outRightOperand.setValue(inLeftOperand * outRightOperand.getValue());
- }
-}
-
diff --git a/docs/rules/AvoidPrintStackTrace.md b/docs/rules/AvoidPrintStackTrace.md
deleted file mode 100644
index c86b53e1..00000000
--- a/docs/rules/AvoidPrintStackTrace.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# AvoidPrintStackTrace
-**Category:** `pmd`
-**Rule Key:** `pmd:AvoidPrintStackTrace`
-> :warning: This rule is **deprecated** in favour of [S1148](https://rules.sonarsource.com/java/RSPEC-1148).
-
------
-
-Avoid printStackTrace(); use a logger call instead.
diff --git a/docs/rules/AvoidProtectedFieldInFinalClass.md b/docs/rules/AvoidProtectedFieldInFinalClass.md
deleted file mode 100644
index baa47ac5..00000000
--- a/docs/rules/AvoidProtectedFieldInFinalClass.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# AvoidProtectedFieldInFinalClass
-**Category:** `pmd`
-**Rule Key:** `pmd:AvoidProtectedFieldInFinalClass`
-> :warning: This rule is **deprecated** in favour of [S2156](https://rules.sonarsource.com/java/RSPEC-2156).
-
------
-
-Do not use protected fields in final classes since they cannot be subclassed. Clarify your intent by using private or package access modifiers instead.
diff --git a/docs/rules/AvoidProtectedMethodInFinalClassNotExtending.md b/docs/rules/AvoidProtectedMethodInFinalClassNotExtending.md
deleted file mode 100644
index d56b5ed2..00000000
--- a/docs/rules/AvoidProtectedMethodInFinalClassNotExtending.md
+++ /dev/null
@@ -1,16 +0,0 @@
-# AvoidProtectedMethodInFinalClassNotExtending
-**Category:** `pmd`
-**Rule Key:** `pmd:AvoidProtectedMethodInFinalClassNotExtending`
-> :warning: This rule is **deprecated** in favour of [S2156](https://rules.sonarsource.com/java/RSPEC-2156).
-
------
-
-Do not use protected methods in most final classes since they cannot be subclassed. This should
-only be allowed in final classes that extend other classes with protected methods (whose
-visibility cannot be reduced). Clarify your intent by using private or package access modifiers instead. Example:
-
-public final class Foo {
- private int bar() {}
- protected int baz() {} // Foo cannot be subclassed, and doesn't extend anything, so is baz() really private or package visible?
-}
-
diff --git a/docs/rules/AvoidReassigningParameters.md b/docs/rules/AvoidReassigningParameters.md
deleted file mode 100644
index bb36e3bd..00000000
--- a/docs/rules/AvoidReassigningParameters.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# AvoidReassigningParameters
-**Category:** `pmd`
-**Rule Key:** `pmd:AvoidReassigningParameters`
-> :warning: This rule is **deprecated** in favour of [S1226](https://rules.sonarsource.com/java/RSPEC-1226).
-
------
-
-Reassigning values to parameters is a questionable practice. Use a temporary local variable instead.
diff --git a/docs/rules/AvoidRethrowingException.md b/docs/rules/AvoidRethrowingException.md
deleted file mode 100644
index e8733058..00000000
--- a/docs/rules/AvoidRethrowingException.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# AvoidRethrowingException
-**Category:** `pmd`
-**Rule Key:** `pmd:AvoidRethrowingException`
-> :warning: This rule is **deprecated** in favour of [S1166](https://rules.sonarsource.com/java/RSPEC-1166).
-
------
-
-Catch blocks that merely rethrow a caught exception only add to code size and runtime complexity.
diff --git a/docs/rules/AvoidStringBufferField.md b/docs/rules/AvoidStringBufferField.md
deleted file mode 100644
index 3ea538bb..00000000
--- a/docs/rules/AvoidStringBufferField.md
+++ /dev/null
@@ -1,13 +0,0 @@
-# AvoidStringBufferField
-**Category:** `pmd`
-**Rule Key:** `pmd:AvoidStringBufferField`
-> :warning: This rule is **deprecated** in favour of [S1149](https://rules.sonarsource.com/java/RSPEC-1149).
-
------
-
-StringBuffers can grow quite a lot, and so may become a source of memory leak (if the owning class has a long life time). Example :
-
-class Foo {
- private StringBuffer memoryLeak;
-}
-
diff --git a/docs/rules/AvoidSynchronizedAtMethodLevel.md b/docs/rules/AvoidSynchronizedAtMethodLevel.md
deleted file mode 100644
index e70ecede..00000000
--- a/docs/rules/AvoidSynchronizedAtMethodLevel.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# AvoidSynchronizedAtMethodLevel
-**Category:** `pmd`
-**Rule Key:** `pmd:AvoidSynchronizedAtMethodLevel`
-
-
------
-
-Method level synchronization can backfire when new code is added to the method. Block-level synchronization helps to ensure that only the code that needs synchronization gets it.
diff --git a/docs/rules/AvoidThreadGroup.md b/docs/rules/AvoidThreadGroup.md
deleted file mode 100644
index 078865e4..00000000
--- a/docs/rules/AvoidThreadGroup.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# AvoidThreadGroup
-**Category:** `pmd`
-**Rule Key:** `pmd:AvoidThreadGroup`
-
-
------
-
-Avoid using ThreadGroup; although it is intended to be used in a threaded environment it contains methods that are not thread safe.
diff --git a/docs/rules/AvoidThrowingNewInstanceOfSameException.md b/docs/rules/AvoidThrowingNewInstanceOfSameException.md
deleted file mode 100644
index 3f5e59e2..00000000
--- a/docs/rules/AvoidThrowingNewInstanceOfSameException.md
+++ /dev/null
@@ -1,20 +0,0 @@
-# AvoidThrowingNewInstanceOfSameException
-**Category:** `pmd`
-**Rule Key:** `pmd:AvoidThrowingNewInstanceOfSameException`
-> :warning: This rule is **deprecated** in favour of [S1166](https://rules.sonarsource.com/java/RSPEC-1166).
-
------
-
-Catch blocks that merely rethrow a caught exception wrapped inside a new instance of the same type only add to code size and runtime complexity. Example :
-
-public class Foo {
- void bar() {
- try {
- // do something
- } catch (SomeException se) {
- // harmless comment
- throw new SomeException(se);
- }
- }
-}
-
diff --git a/docs/rules/AvoidThrowingNullPointerException.md b/docs/rules/AvoidThrowingNullPointerException.md
deleted file mode 100644
index 3a2d1ef9..00000000
--- a/docs/rules/AvoidThrowingNullPointerException.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# AvoidThrowingNullPointerException
-**Category:** `pmd`
-**Rule Key:** `pmd:AvoidThrowingNullPointerException`
-> :warning: This rule is **deprecated** in favour of [S1695](https://rules.sonarsource.com/java/RSPEC-1695).
-
------
-
-Avoid throwing a NullPointerException - it's confusing because most people will assume that the virtual machine threw it. Consider using an IllegalArgumentException instead; this will be clearly seen as a programmer-initiated exception.
diff --git a/docs/rules/AvoidThrowingRawExceptionTypes.md b/docs/rules/AvoidThrowingRawExceptionTypes.md
deleted file mode 100644
index fc800acd..00000000
--- a/docs/rules/AvoidThrowingRawExceptionTypes.md
+++ /dev/null
@@ -1,11 +0,0 @@
-# AvoidThrowingRawExceptionTypes
-**Category:** `pmd`
-**Rule Key:** `pmd:AvoidThrowingRawExceptionTypes`
-> :warning: This rule is **deprecated** in favour of [S00112](https://rules.sonarsource.com/java/RSPEC-112).
-
------
-
-
-**Rule Key:** `pmd:AvoidUsingHardCodedIP`
-> :warning: This rule is **deprecated** in favour of [S1313](https://rules.sonarsource.com/java/RSPEC-1313).
-
------
-
-An application with hard-coded IP addresses can become impossible to deploy in some cases. Externalizing IP addresses is preferable.
diff --git a/docs/rules/AvoidUsingNativeCode.md b/docs/rules/AvoidUsingNativeCode.md
deleted file mode 100644
index 8d8fab0f..00000000
--- a/docs/rules/AvoidUsingNativeCode.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# AvoidUsingNativeCode
-**Category:** `pmd`
-**Rule Key:** `pmd:AvoidUsingNativeCode`
-
-
------
-
-As JVM and Java language offer already many help in creating application, it should be very rare to have to rely on non-java code. Even though, it is rare to actually have to use Java Native Interface (JNI). As the use of JNI make application less portable, and harder to maintain, it is not recommended.
diff --git a/docs/rules/AvoidUsingOctalValues.md b/docs/rules/AvoidUsingOctalValues.md
deleted file mode 100644
index 596a3529..00000000
--- a/docs/rules/AvoidUsingOctalValues.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# AvoidUsingOctalValues
-**Category:** `pmd`
-**Rule Key:** `pmd:AvoidUsingOctalValues`
-> :warning: This rule is **deprecated** in favour of [S1314](https://rules.sonarsource.com/java/RSPEC-1314).
-
------
-
-Integer literals should not start with zero. Zero means that the rest of literal will be interpreted as an octal value.
diff --git a/docs/rules/AvoidUsingShortType.md b/docs/rules/AvoidUsingShortType.md
deleted file mode 100644
index d4de59d9..00000000
--- a/docs/rules/AvoidUsingShortType.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# AvoidUsingShortType
-**Category:** `pmd`
-**Rule Key:** `pmd:AvoidUsingShortType`
-
-
------
-
-Java uses the short type to reduce memory usage, not to optimize calculation. On the contrary, the JVM does not have arithmetic capabilities with the type short. So, the P-code must convert the short into int, then do the proper calculation and then again, convert int to short. So, use of the short type may have a great effect on memory usage.
diff --git a/docs/rules/AvoidUsingVolatile.md b/docs/rules/AvoidUsingVolatile.md
deleted file mode 100644
index d0921366..00000000
--- a/docs/rules/AvoidUsingVolatile.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# AvoidUsingVolatile
-**Category:** `pmd`
-**Rule Key:** `pmd:AvoidUsingVolatile`
-
-
------
-
-Use of the keyword "volatile" is general used to fine tune a Java application, and therefore, requires a good expertise of the Java Memory Model. Morover, its range of action is somewhat misknown. Therefore, the volatile keyword should not be used for maintenance purpose and portability.
diff --git a/docs/rules/BadComparison.md b/docs/rules/BadComparison.md
deleted file mode 100644
index 439740e5..00000000
--- a/docs/rules/BadComparison.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# BadComparison
-**Category:** `pmd`
-**Rule Key:** `pmd:BadComparison`
-
-
------
-
-Avoid equality comparisons with Double.NaN - these are likely to be logic errors.
diff --git a/docs/rules/BeanMembersShouldSerialize.md b/docs/rules/BeanMembersShouldSerialize.md
deleted file mode 100644
index 99895f33..00000000
--- a/docs/rules/BeanMembersShouldSerialize.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# BeanMembersShouldSerialize
-**Category:** `pmd`
-**Rule Key:** `pmd:BeanMembersShouldSerialize`
-
-
------
-
-If a class is a bean, or is referenced by a bean directly or indirectly it needs to be serializable. Member variables need to be marked as transient, static, or have accessor methods in the class. Marking variables as transient is the safest and easiest modification. Accessor methods should follow the Java naming conventions, i.e.if you have a variable foo, you should provide getFoo and setFoo methods.
diff --git a/docs/rules/BigIntegerInstantiation.md b/docs/rules/BigIntegerInstantiation.md
deleted file mode 100644
index 8570a886..00000000
--- a/docs/rules/BigIntegerInstantiation.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# BigIntegerInstantiation
-**Category:** `pmd`
-**Rule Key:** `pmd:BigIntegerInstantiation`
-
-
------
-
-Don't create instances of already existing BigInteger (BigInteger.ZERO, BigInteger.ONE) and for 1.5 on, BigInteger.TEN and BigDecimal (BigDecimal.ZERO, BigDecimal.ONE, BigDecimal.TEN)
diff --git a/docs/rules/BooleanGetMethodName.md b/docs/rules/BooleanGetMethodName.md
deleted file mode 100644
index e7911cc4..00000000
--- a/docs/rules/BooleanGetMethodName.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# BooleanGetMethodName
-**Category:** `pmd`
-**Rule Key:** `pmd:BooleanGetMethodName`
-
-
------
-
-Looks for methods named "getX()" with "boolean" as the return type. The convention is to name these methods "isX()".
diff --git a/docs/rules/BooleanInstantiation.md b/docs/rules/BooleanInstantiation.md
deleted file mode 100644
index 9663e462..00000000
--- a/docs/rules/BooleanInstantiation.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# BooleanInstantiation
-**Category:** `pmd`
-**Rule Key:** `pmd:BooleanInstantiation`
-
-
------
-
-Avoid instantiating Boolean objects; you can reference Boolean.TRUE, Boolean.FALSE, or call Boolean.valueOf() instead.
diff --git a/docs/rules/BrokenNullCheck.md b/docs/rules/BrokenNullCheck.md
deleted file mode 100644
index 757fbf9a..00000000
--- a/docs/rules/BrokenNullCheck.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# BrokenNullCheck
-**Category:** `pmd`
-**Rule Key:** `pmd:BrokenNullCheck`
-> :warning: This rule is **deprecated** in favour of [S1697](https://rules.sonarsource.com/java/RSPEC-1697).
-
------
-
-The null check is broken since it will throw a Nullpointer itself. The reason is that a method is called on the object when it is null. It is likely that you used || instead of && or vice versa.
diff --git a/docs/rules/ByteInstantiation.md b/docs/rules/ByteInstantiation.md
deleted file mode 100644
index 452cdeee..00000000
--- a/docs/rules/ByteInstantiation.md
+++ /dev/null
@@ -1,14 +0,0 @@
-# ByteInstantiation
-**Category:** `pmd`
-**Rule Key:** `pmd:ByteInstantiation`
-
-
------
-
-In JDK 1.5, calling new Byte() causes memory allocation. Byte.valueOf() is more memory friendly. Example :
-
-public class Foo {
-private Byte i = new Byte(0); // change to Byte i =
-Byte.valueOf(0);
-}
-
diff --git a/docs/rules/CallSuperFirst.md b/docs/rules/CallSuperFirst.md
deleted file mode 100644
index f9775f42..00000000
--- a/docs/rules/CallSuperFirst.md
+++ /dev/null
@@ -1,16 +0,0 @@
-# CallSuperFirst
-**Category:** `pmd`
-**Rule Key:** `pmd:CallSuperFirst`
-
-
------
-
-Super should be called at the start of the method. Example :
-
-public class DummyActivity extends Activity {
- public void onCreate(Bundle bundle) {
- // missing call to super.onCreate(bundle)
- foo();
- }
-}
-
diff --git a/docs/rules/CallSuperInConstructor.md b/docs/rules/CallSuperInConstructor.md
deleted file mode 100644
index 27f149e4..00000000
--- a/docs/rules/CallSuperInConstructor.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# CallSuperInConstructor
-**Category:** `pmd`
-**Rule Key:** `pmd:CallSuperInConstructor`
-
-
------
-
-It is a good practice to call super() in a constructor. If super() is not called but another constructor (such as an overloaded constructor) is called, this rule will not report it.
diff --git a/docs/rules/CallSuperLast.md b/docs/rules/CallSuperLast.md
deleted file mode 100644
index d80f3934..00000000
--- a/docs/rules/CallSuperLast.md
+++ /dev/null
@@ -1,16 +0,0 @@
-# CallSuperLast
-**Category:** `pmd`
-**Rule Key:** `pmd:CallSuperLast`
-
-
------
-
-Super should be called at the end of the method. Example :
-
-public class DummyActivity extends Activity {
- public void onPause() {
- foo();
- // missing call to super.onPause()
- }
-}
-
diff --git a/docs/rules/CheckResultSet.md b/docs/rules/CheckResultSet.md
deleted file mode 100644
index 6cf54d3d..00000000
--- a/docs/rules/CheckResultSet.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# CheckResultSet
-**Category:** `pmd`
-**Rule Key:** `pmd:CheckResultSet`
-
-
------
-
-Always check the return of one of the navigation method (next,previous,first,last) of a ResultSet. Indeed, if the value return is "false", the developer should deal with it !
diff --git a/docs/rules/CheckSkipResult.md b/docs/rules/CheckSkipResult.md
deleted file mode 100644
index 32d69367..00000000
--- a/docs/rules/CheckSkipResult.md
+++ /dev/null
@@ -1,26 +0,0 @@
-# CheckSkipResult
-**Category:** `pmd`
-**Rule Key:** `pmd:CheckSkipResult`
-> :warning: This rule is **deprecated** in favour of [S2674](https://rules.sonarsource.com/java/RSPEC-2674).
-
------
-
-The skip() method may skip a smaller number of bytes than requested. Check the returned value to find out if it was the case or not. Example:
-
-public class Foo {
-
- private FileInputStream _s = new FileInputStream("file");
-
- public void skip(int n) throws IOException {
- _s.skip(n); // You are not sure that exactly n bytes are skipped
- }
-
- public void skipExactly(int n) throws IOException {
- while (n != 0) {
- long skipped = _s.skip(n);
- if (skipped == 0)
- throw new EOFException();
- n -= skipped;
- }
- }
-
diff --git a/docs/rules/ClassCastExceptionWithToArray.md b/docs/rules/ClassCastExceptionWithToArray.md
deleted file mode 100644
index b883d1c6..00000000
--- a/docs/rules/ClassCastExceptionWithToArray.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# ClassCastExceptionWithToArray
-**Category:** `pmd`
-**Rule Key:** `pmd:ClassCastExceptionWithToArray`
-
-
------
-
-if you need to get an array of a class from your Collection, you should pass an array of the desidered class as the parameter of the toArray method. Otherwise you will get a ClassCastException.
diff --git a/docs/rules/ClassNamingConventions.md b/docs/rules/ClassNamingConventions.md
deleted file mode 100644
index 0335f144..00000000
--- a/docs/rules/ClassNamingConventions.md
+++ /dev/null
@@ -1,10 +0,0 @@
-# ClassNamingConventions
-**Category:** `pmd`
-**Rule Key:** `pmd:ClassNamingConventions`
-> :warning: This rule is **deprecated** in favour of [S00101](https://rules.sonarsource.com/java/RSPEC-101), [S00114](https://rules.sonarsource.com/java/RSPEC-114).
-
------
-
-
-**Rule Key:** `pmd:ClassWithOnlyPrivateConstructorsShouldBeFinal`
-> :warning: This rule is **deprecated** in favour of [S2974](https://rules.sonarsource.com/java/RSPEC-2974).
-
------
-
-A class with only private constructors should be final, unless the private constructor is called by a inner class. Example :
-
-public class Foo { //Should be final
- private Foo() { }
-}
-
diff --git a/docs/rules/CloneMethodMustBePublic.md b/docs/rules/CloneMethodMustBePublic.md
deleted file mode 100644
index aafe71c9..00000000
--- a/docs/rules/CloneMethodMustBePublic.md
+++ /dev/null
@@ -1,31 +0,0 @@
-# CloneMethodMustBePublic
-**Category:** `pmd`
-**Rule Key:** `pmd:CloneMethodMustBePublic`
-
-
------
-
-
-public class Foo implements Cloneable {
- @Override
- protected Object clone() throws CloneNotSupportedException { // Violation, must be public
- }
-}
-
-public class Foo implements Cloneable {
- @Override
- protected Foo clone() { // Violation, must be public
- }
-}
-
-public class Foo implements Cloneable {
- @Override
- public Object clone() // Ok
-}
-
diff --git a/docs/rules/CloneMethodMustImplementCloneable.md b/docs/rules/CloneMethodMustImplementCloneable.md
deleted file mode 100644
index e5fb30da..00000000
--- a/docs/rules/CloneMethodMustImplementCloneable.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# CloneMethodMustImplementCloneable
-**Category:** `pmd`
-**Rule Key:** `pmd:CloneMethodMustImplementCloneable`
-> :warning: This rule is **deprecated** in favour of [S1182](https://rules.sonarsource.com/java/RSPEC-1182).
-
------
-
-The method clone() should only be implemented if the class implements the Cloneable interface with the exception of a final method that only throws CloneNotSupportedException.
diff --git a/docs/rules/CloneMethodMustImplementCloneableWithTypeResolution.md b/docs/rules/CloneMethodMustImplementCloneableWithTypeResolution.md
deleted file mode 100644
index f7e7e0c4..00000000
--- a/docs/rules/CloneMethodMustImplementCloneableWithTypeResolution.md
+++ /dev/null
@@ -1,17 +0,0 @@
-# CloneMethodMustImplementCloneableWithTypeResolution
-**Category:** `pmd`
-**Rule Key:** `pmd:CloneMethodMustImplementCloneableWithTypeResolution`
-> :warning: This rule is **deprecated** in favour of [S1182](https://rules.sonarsource.com/java/RSPEC-1182).
-
------
-
-The method clone() should only be implemented if the class implements the Cloneable interface with the exception
-of a final method that only throws CloneNotSupportedException. This version uses PMD's type resolution facilities,
-and can detect if the class implements or extends a Cloneable class. Example:
-
-public class MyClass {
- public Object clone() throws CloneNotSupportedException {
- return foo;
- }
-}
-
diff --git a/docs/rules/CloneMethodReturnTypeMustMatchClassName.md b/docs/rules/CloneMethodReturnTypeMustMatchClassName.md
deleted file mode 100644
index 444ed80c..00000000
--- a/docs/rules/CloneMethodReturnTypeMustMatchClassName.md
+++ /dev/null
@@ -1,30 +0,0 @@
-# CloneMethodReturnTypeMustMatchClassName
-**Category:** `pmd`
-**Rule Key:** `pmd:CloneMethodReturnTypeMustMatchClassName`
-
-
------
-
-
-public class Foo implements Cloneable {
- @Override
- protected Object clone() { // Violation, Object must be Foo
- }
-}
-
-public class Foo implements Cloneable {
- @Override
- public Foo clone() { //Ok
- }
-}
-
diff --git a/docs/rules/CloneThrowsCloneNotSupportedException.md b/docs/rules/CloneThrowsCloneNotSupportedException.md
deleted file mode 100644
index b0b4a928..00000000
--- a/docs/rules/CloneThrowsCloneNotSupportedException.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# CloneThrowsCloneNotSupportedException
-**Category:** `pmd`
-**Rule Key:** `pmd:CloneThrowsCloneNotSupportedException`
-> :warning: This rule is **deprecated** in favour of [S1182](https://rules.sonarsource.com/java/RSPEC-1182).
-
------
-
-The method clone() should throw a CloneNotSupportedException.
diff --git a/docs/rules/CloseResource.md b/docs/rules/CloseResource.md
deleted file mode 100644
index e83047e3..00000000
--- a/docs/rules/CloseResource.md
+++ /dev/null
@@ -1,16 +0,0 @@
-# CloseResource
-**Category:** `pmd`
-**Rule Key:** `pmd:CloseResource`
-> :warning: This rule is **deprecated** in favour of [S2095](https://rules.sonarsource.com/java/RSPEC-2095).
-
------
-
-Ensure that resources (like Connection, Statement, and ResultSet objects) are always closed after use. It does this by looking for code patterned like :
-
-Connection c = openConnection();
-try {
- // do stuff, and maybe catch something
-} finally {
- c.close();
-}
-
diff --git a/docs/rules/CollapsibleIfStatements.md b/docs/rules/CollapsibleIfStatements.md
deleted file mode 100644
index bdfc6857..00000000
--- a/docs/rules/CollapsibleIfStatements.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# CollapsibleIfStatements
-**Category:** `pmd`
-**Rule Key:** `pmd:CollapsibleIfStatements`
-> :warning: This rule is **deprecated** in favour of [S1066](https://rules.sonarsource.com/java/RSPEC-1066).
-
------
-
-Sometimes two 'if' statements can be consolidated by separating their conditions with a boolean short-circuit operator.
diff --git a/docs/rules/CommentContent.md b/docs/rules/CommentContent.md
deleted file mode 100644
index 41585c9e..00000000
--- a/docs/rules/CommentContent.md
+++ /dev/null
@@ -1,11 +0,0 @@
-# CommentContent
-**Category:** `pmd`
-**Rule Key:** `pmd:CommentContent`
-
-
------
-
-A rule for the politically correct... we don't want to offend anyone. Example:
-
-// OMG, this is horrible, Bob is an idiot !!!
-
diff --git a/docs/rules/CommentDefaultAccessModifier.md b/docs/rules/CommentDefaultAccessModifier.md
deleted file mode 100644
index 8c54f317..00000000
--- a/docs/rules/CommentDefaultAccessModifier.md
+++ /dev/null
@@ -1,35 +0,0 @@
-# CommentDefaultAccessModifier
-**Category:** `pmd`
-**Rule Key:** `pmd:CommentDefaultAccessModifier`
-
-
------
-
-
-public class Foo {
- final String stringValue = "some string";
- String getString() {
- return stringValue;
- }
-
- class NestedFoo {
- }
-}
-
-// should be
-public class Foo {
- /* default */ final String stringValue = "some string";
- /* default */ String getString() {
- return stringValue;
- }
-
- /* default */ class NestedFoo {
- }
-}
-
diff --git a/docs/rules/CommentRequired.md b/docs/rules/CommentRequired.md
deleted file mode 100644
index 34af27b5..00000000
--- a/docs/rules/CommentRequired.md
+++ /dev/null
@@ -1,15 +0,0 @@
-# CommentRequired
-**Category:** `pmd`
-**Rule Key:** `pmd:CommentRequired`
-
-
------
-
-Denotes whether comments are required (or unwanted) for specific language elements. Example:
-
-/**
-*
-*
-* @author George Bush
-*/
-
diff --git a/docs/rules/CommentSize.md b/docs/rules/CommentSize.md
deleted file mode 100644
index 80bfc6df..00000000
--- a/docs/rules/CommentSize.md
+++ /dev/null
@@ -1,26 +0,0 @@
-# CommentSize
-**Category:** `pmd`
-**Rule Key:** `pmd:CommentSize`
-
-
------
-
-Determines whether the dimensions of non-header comments found are within the specified limits. Example:
-
-/**
-*
-* too many lines!
-*
-*
-*
-*
-*
-*
-*
-*
-*
-*
-*
-*
-*/
-
diff --git a/docs/rules/CompareObjectsWithEquals.md b/docs/rules/CompareObjectsWithEquals.md
deleted file mode 100644
index 89912807..00000000
--- a/docs/rules/CompareObjectsWithEquals.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# CompareObjectsWithEquals
-**Category:** `pmd`
-**Rule Key:** `pmd:CompareObjectsWithEquals`
-> :warning: This rule is **deprecated** in favour of [S1698](https://rules.sonarsource.com/java/RSPEC-1698).
-
------
-
-Use equals() to compare object references; avoid comparing them with ==.
diff --git a/docs/rules/ConfusingTernary.md b/docs/rules/ConfusingTernary.md
deleted file mode 100644
index a4759098..00000000
--- a/docs/rules/ConfusingTernary.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# ConfusingTernary
-**Category:** `pmd`
-**Rule Key:** `pmd:ConfusingTernary`
-
-
------
-
-In an if expression with an else clause, avoid negation in the test. For example, rephrase: if (x != y) diff(); else same(); as: if (x == y) same(); else diff(); Most if (x != y) cases without an else are often return cases, so consistent use of this rule makes the code easier to read. Also, this resolves trivial ordering problems, such as does the error case go first? or does the common case go first?.
diff --git a/docs/rules/ConsecutiveAppendsShouldReuse.md b/docs/rules/ConsecutiveAppendsShouldReuse.md
deleted file mode 100644
index 3bbf3545..00000000
--- a/docs/rules/ConsecutiveAppendsShouldReuse.md
+++ /dev/null
@@ -1,19 +0,0 @@
-# ConsecutiveAppendsShouldReuse
-**Category:** `pmd`
-**Rule Key:** `pmd:ConsecutiveAppendsShouldReuse`
-
-
------
-
-Consecutively calls to StringBuffer/StringBuilder .append should reuse the target object. This can improve the performance. Example:
-
-String foo = " ";
-
-StringBuffer buf = new StringBuffer();
-buf.append("Hello"); // poor
-buf.append(foo);
-buf.append("World");
-
-StringBuffer buf = new StringBuffer();
-buf.append("Hello").append(foo).append("World"); // good
-
diff --git a/docs/rules/ConsecutiveLiteralAppends.md b/docs/rules/ConsecutiveLiteralAppends.md
deleted file mode 100644
index d7a1cb7c..00000000
--- a/docs/rules/ConsecutiveLiteralAppends.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# ConsecutiveLiteralAppends
-**Category:** `pmd`
-**Rule Key:** `pmd:ConsecutiveLiteralAppends`
-
-
------
-
-Consecutively calling StringBuffer.append with String literals
diff --git a/docs/rules/ConstructorCallsOverridableMethod.md b/docs/rules/ConstructorCallsOverridableMethod.md
deleted file mode 100644
index 4d5b9da8..00000000
--- a/docs/rules/ConstructorCallsOverridableMethod.md
+++ /dev/null
@@ -1,34 +0,0 @@
-# ConstructorCallsOverridableMethod
-**Category:** `pmd`
-**Rule Key:** `pmd:ConstructorCallsOverridableMethod`
-> :warning: This rule is **deprecated** in favour of [S1699](https://rules.sonarsource.com/java/RSPEC-1699).
-
------
-
-Calling overridable methods during construction poses a risk of invoking methods on an incompletely constructed object
-and can be difficult to discern. It may leave the sub-class unable to construct its superclass or forced to replicate
-the construction process completely within itself, losing the ability to call super().
-If the default constructor contains a call to an overridable method, the subclass may be completely uninstantiable.
-Note that this includes method calls throughout the control flow graph - i.e., if a constructor Foo() calls
-a private method bar() that calls a public method buz(), this denotes a problem.
-
Example :
-
-public class SeniorClass {
- public SeniorClass(){
- toString(); //may throw NullPointerException if overridden
- }
- public String toString(){
- return "IAmSeniorClass";
- }
-}
-public class JuniorClass extends SeniorClass {
- private String name;
- public JuniorClass(){
- super(); //Automatic call leads to NullPointerException
- name = "JuniorClass";
- }
- public String toString(){
- return name.toUpperCase();
- }
-}
-
diff --git a/docs/rules/CouplingBetweenObjects.md b/docs/rules/CouplingBetweenObjects.md
deleted file mode 100644
index 97ca1efd..00000000
--- a/docs/rules/CouplingBetweenObjects.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# CouplingBetweenObjects
-**Category:** `pmd`
-**Rule Key:** `pmd:CouplingBetweenObjects`
-> :warning: This rule is **deprecated** in favour of [S1200](https://rules.sonarsource.com/java/RSPEC-1200).
-
------
-
-This rule counts unique attributes, local variables and return types within an object. A number higher than specified threshold can indicate a high degree of coupling.
diff --git a/docs/rules/CyclomaticComplexity.md b/docs/rules/CyclomaticComplexity.md
deleted file mode 100644
index 755885f5..00000000
--- a/docs/rules/CyclomaticComplexity.md
+++ /dev/null
@@ -1,12 +0,0 @@
-# CyclomaticComplexity
-**Category:** `pmd`
-**Rule Key:** `pmd:CyclomaticComplexity`
-> :warning: This rule is **deprecated** in favour of `squid:MethodCyclomaticComplexity`, `squid:ClassCyclomaticComplexity`.
-
------
-
-
-**Rule Key:** `pmd:DataflowAnomalyAnalysis`
-
-
------
-
-The dataflow analysis tracks local definitions, undefinitions and references to variables on different paths on the data flow. From those informations there can be found various problems. 1. UR - Anomaly: There is a reference to a variable that was not defined before. This is a bug and leads to an error. 2. DU - Anomaly: A recently defined variable is undefined. These anomalies may appear in normal source text. 3. DD - Anomaly: A recently defined variable is redefined. This is ominous but don't have to be a bug.
diff --git a/docs/rules/DefaultLabelNotLastInSwitchStmt.md b/docs/rules/DefaultLabelNotLastInSwitchStmt.md
deleted file mode 100644
index 62238f10..00000000
--- a/docs/rules/DefaultLabelNotLastInSwitchStmt.md
+++ /dev/null
@@ -1,22 +0,0 @@
-# DefaultLabelNotLastInSwitchStmt
-**Category:** `pmd`
-**Rule Key:** `pmd:DefaultLabelNotLastInSwitchStmt`
-> :warning: This rule is **deprecated** in favour of `squid:SwitchLastCaseIsDefaultCheck`.
-
------
-
-Switch statements should have a default label. Example :
-
-public class Foo {
- void bar(int a) {
- switch (a) {
- case 1: // do something
- break;
- default: // the default case should be last, by convention
- break;
- case 2:
- break;
- }
- }
-}
-
diff --git a/docs/rules/DefaultPackage.md b/docs/rules/DefaultPackage.md
deleted file mode 100644
index 2631e81f..00000000
--- a/docs/rules/DefaultPackage.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# DefaultPackage
-**Category:** `pmd`
-**Rule Key:** `pmd:DefaultPackage`
-
-
------
-
-Use explicit scoping instead of the default package private level.
diff --git a/docs/rules/DoNotCallGarbageCollectionExplicitly.md b/docs/rules/DoNotCallGarbageCollectionExplicitly.md
deleted file mode 100644
index 15a774f4..00000000
--- a/docs/rules/DoNotCallGarbageCollectionExplicitly.md
+++ /dev/null
@@ -1,27 +0,0 @@
-# DoNotCallGarbageCollectionExplicitly
-**Category:** `pmd`
-**Rule Key:** `pmd:DoNotCallGarbageCollectionExplicitly`
-> :warning: This rule is **deprecated** in favour of [S1215](https://rules.sonarsource.com/java/RSPEC-1215).
-
------
-
-Calls to System.gc(), Runtime.getRuntime().gc(), and System.runFinalization() are not advised. Code should have the same behavior whether the garbage collection is disabled using the option -Xdisableexplicitgc or not. Moreover, "modern" jvms do a very good job handling garbage collections. If memory usage issues unrelated to memory leaks develop within an application, it should be dealt with JVM options rather than within the code itself. Example :
-
- public class GCCall
-{
- public GCCall()
- {
- // Explicit gc call !
- System.gc();
- }
- public void doSomething()
- {
- // Explicit gc call !
- Runtime.getRuntime().gc();
- }
-
- public explicitGCcall() { // Explicit gc call ! System.gc(); }
-
- public void doSomething() { // Explicit gc call ! Runtime.getRuntime().gc(); }
-}
-
diff --git a/docs/rules/DoNotCallSystemExit.md b/docs/rules/DoNotCallSystemExit.md
deleted file mode 100644
index c8b06fee..00000000
--- a/docs/rules/DoNotCallSystemExit.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# DoNotCallSystemExit
-**Category:** `pmd`
-**Rule Key:** `pmd:DoNotCallSystemExit`
-> :warning: This rule is **deprecated** in favour of [S1147](https://rules.sonarsource.com/java/RSPEC-1147).
-
------
-
-Web applications should not call System.exit(), since only the web container or the application server should stop the JVM.
diff --git a/docs/rules/DoNotExtendJavaLangError.md b/docs/rules/DoNotExtendJavaLangError.md
deleted file mode 100644
index 75b593f8..00000000
--- a/docs/rules/DoNotExtendJavaLangError.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# DoNotExtendJavaLangError
-**Category:** `pmd`
-**Rule Key:** `pmd:DoNotExtendJavaLangError`
-> :warning: This rule is **deprecated** in favour of [S1194](https://rules.sonarsource.com/java/RSPEC-1194).
-
------
-
-Errors are system exceptions. Do not extend them.
diff --git a/docs/rules/DoNotHardCodeSDCard.md b/docs/rules/DoNotHardCodeSDCard.md
deleted file mode 100644
index 383b9d4f..00000000
--- a/docs/rules/DoNotHardCodeSDCard.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# DoNotHardCodeSDCard
-**Category:** `pmd`
-**Rule Key:** `pmd:DoNotHardCodeSDCard`
-
-
------
-
-Use Environment.getExternalStorageDirectory() instead of "/sdcard".
diff --git a/docs/rules/DoNotThrowExceptionInFinally.md b/docs/rules/DoNotThrowExceptionInFinally.md
deleted file mode 100644
index a4f1741c..00000000
--- a/docs/rules/DoNotThrowExceptionInFinally.md
+++ /dev/null
@@ -1,27 +0,0 @@
-# DoNotThrowExceptionInFinally
-**Category:** `pmd`
-**Rule Key:** `pmd:DoNotThrowExceptionInFinally`
-> :warning: This rule is **deprecated** in favour of [S1163](https://rules.sonarsource.com/java/RSPEC-1163).
-
------
-
-Throwing exception in a finally block is confusing. It may mask exception or a defect of the code, it also render code cleanup uninstable. Example :
-
-public class Foo
-{
- public void bar()
- {
- try {
- // Here do some stuff
- }
- catch( Exception e) {
- // Handling the issue
- }
- finally
- {
- // is this really a good idea ?
- throw new Exception();
- }
- }
-}
-
diff --git a/docs/rules/DoNotUseThreads.md b/docs/rules/DoNotUseThreads.md
deleted file mode 100644
index 7ce2b2a9..00000000
--- a/docs/rules/DoNotUseThreads.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# DoNotUseThreads
-**Category:** `pmd`
-**Rule Key:** `pmd:DoNotUseThreads`
-
-
------
-
-The J2EE specification explicitly forbid use of threads.
diff --git a/docs/rules/DontCallThreadRun.md b/docs/rules/DontCallThreadRun.md
deleted file mode 100644
index c4672c69..00000000
--- a/docs/rules/DontCallThreadRun.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# DontCallThreadRun
-**Category:** `pmd`
-**Rule Key:** `pmd:DontCallThreadRun`
-> :warning: This rule is **deprecated** in favour of [S1217](https://rules.sonarsource.com/java/RSPEC-1217).
-
------
-
-Explicitly calling Thread.run() method will execute in the caller's thread of control. Instead, call Thread.start() for the intended behavior.
diff --git a/docs/rules/DontImportJavaLang.md b/docs/rules/DontImportJavaLang.md
deleted file mode 100644
index 4922ecf3..00000000
--- a/docs/rules/DontImportJavaLang.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# DontImportJavaLang
-**Category:** `pmd`
-**Rule Key:** `pmd:DontImportJavaLang`
-> :warning: This rule is **deprecated** in favour of `squid:UselessImportCheck`.
-
------
-
-Avoid importing anything from the package 'java.lang'. These classes are automatically imported (JLS 7.5.3).
diff --git a/docs/rules/DontImportSun.md b/docs/rules/DontImportSun.md
deleted file mode 100644
index 40e097c1..00000000
--- a/docs/rules/DontImportSun.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# DontImportSun
-**Category:** `pmd`
-**Rule Key:** `pmd:DontImportSun`
-> :warning: This rule is **deprecated** in favour of [S1191](https://rules.sonarsource.com/java/RSPEC-1191).
-
------
-
-Avoid importing anything from the 'sun.*' packages. These packages are not portable and are likely to change.
diff --git a/docs/rules/DontUseFloatTypeForLoopIndices.md b/docs/rules/DontUseFloatTypeForLoopIndices.md
deleted file mode 100644
index 49c5390e..00000000
--- a/docs/rules/DontUseFloatTypeForLoopIndices.md
+++ /dev/null
@@ -1,23 +0,0 @@
-# DontUseFloatTypeForLoopIndices
-**Category:** `pmd`
-**Rule Key:** `pmd:DontUseFloatTypeForLoopIndices`
-
-
------
-
-Don't use floating point for loop indices. If you must use floating point, use double
-unless you're certain that float provides enough precision and you have a compelling
-performance need (space or time). Example:
-
-public class Count {
- public static void main(String[] args) {
- final int START = 2000000000;
- int count = 0;
- for (float f = START; f < START + 50; f++)
- count++;
- //Prints 0 because (float) START == (float) (START + 50).
- System.out.println(count);
- //The termination test misbehaves due to floating point granularity.
- }
-}
-
diff --git a/docs/rules/DoubleCheckedLocking.md b/docs/rules/DoubleCheckedLocking.md
deleted file mode 100644
index c171778a..00000000
--- a/docs/rules/DoubleCheckedLocking.md
+++ /dev/null
@@ -1,24 +0,0 @@
-# DoubleCheckedLocking
-**Category:** `pmd`
-**Rule Key:** `pmd:DoubleCheckedLocking`
-
-
------
-
-Partially created objects can be returned by the Double Checked Locking pattern when used in Java. An optimizing JRE may assign a reference to the baz variable before it creates the object the reference is intended to point to.
-More details. Example :
-
-public class Foo {
- Object baz;
- Object bar() {
- if(baz == null) { //baz may be non-null yet not fully created
- synchronized(this){
- if(baz == null){
- baz = new Object();
- }
- }
- }
- return baz;
- }
-}
-
diff --git a/docs/rules/DuplicateImports.md b/docs/rules/DuplicateImports.md
deleted file mode 100644
index 549f6c47..00000000
--- a/docs/rules/DuplicateImports.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# DuplicateImports
-**Category:** `pmd`
-**Rule Key:** `pmd:DuplicateImports`
-> :warning: This rule is **deprecated** in favour of `squid:UselessImportCheck`.
-
------
-
-Avoid duplicate import statements.
diff --git a/docs/rules/EmptyCatchBlock.md b/docs/rules/EmptyCatchBlock.md
deleted file mode 100644
index f868e997..00000000
--- a/docs/rules/EmptyCatchBlock.md
+++ /dev/null
@@ -1,11 +0,0 @@
-# EmptyCatchBlock
-**Category:** `pmd`
-**Rule Key:** `pmd:EmptyCatchBlock`
-> :warning: This rule is **deprecated** in favour of [S00108](https://rules.sonarsource.com/java/RSPEC-108).
-
------
-
-
-**Rule Key:** `pmd:EmptyFinalizer`
-> :warning: This rule is **deprecated** in favour of [S1186](https://rules.sonarsource.com/java/RSPEC-1186).
-
------
-
-
-**Rule Key:** `pmd:EmptyFinallyBlock`
-> :warning: This rule is **deprecated** in favour of [S00108](https://rules.sonarsource.com/java/RSPEC-108).
-
------
-
-
-**Rule Key:** `pmd:EmptyIfStmt`
-> :warning: This rule is **deprecated** in favour of [S00108](https://rules.sonarsource.com/java/RSPEC-108).
-
------
-
-
-**Rule Key:** `pmd:EmptyInitializer`
-> :warning: This rule is **deprecated** in favour of [S00108](https://rules.sonarsource.com/java/RSPEC-108).
-
------
-
-An empty initializer was found. Example :
-
-public class Foo {
-
- static {} // Why ?
-
- {} // Again, why ?
-
-}
-
diff --git a/docs/rules/EmptyMethodInAbstractClassShouldBeAbstract.md b/docs/rules/EmptyMethodInAbstractClassShouldBeAbstract.md
deleted file mode 100644
index 435ab6d3..00000000
--- a/docs/rules/EmptyMethodInAbstractClassShouldBeAbstract.md
+++ /dev/null
@@ -1,22 +0,0 @@
-# EmptyMethodInAbstractClassShouldBeAbstract
-**Category:** `pmd`
-**Rule Key:** `pmd:EmptyMethodInAbstractClassShouldBeAbstract`
-
-
------
-
-An empty method in an abstract class should be abstract instead, as developer may rely on this empty implementation rather than code the appropriate one.
-
-public abstract class ShouldBeAbstract
-{
- public Object couldBeAbstract()
- {
- // Should be abstract method ?
- return null;
- }
-
- public void couldBeAbstract()
- {
- }
-}
-
diff --git a/docs/rules/EmptyStatementBlock.md b/docs/rules/EmptyStatementBlock.md
deleted file mode 100644
index 7e9dc1cb..00000000
--- a/docs/rules/EmptyStatementBlock.md
+++ /dev/null
@@ -1,20 +0,0 @@
-# EmptyStatementBlock
-**Category:** `pmd`
-**Rule Key:** `pmd:EmptyStatementBlock`
-> :warning: This rule is **deprecated** in favour of [S00108](https://rules.sonarsource.com/java/RSPEC-108).
-
------
-
-Empty block statements serve no purpose and should be removed. Example:
-
-public class Foo {
-
- private int _bar;
-
- public void setBar(int bar) {
- { _bar = bar; } // Why not?
- {} // But remove this.
- }
-
-}
-
diff --git a/docs/rules/EmptyStatementNotInLoop.md b/docs/rules/EmptyStatementNotInLoop.md
deleted file mode 100644
index 856200dd..00000000
--- a/docs/rules/EmptyStatementNotInLoop.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# EmptyStatementNotInLoop
-**Category:** `pmd`
-**Rule Key:** `pmd:EmptyStatementNotInLoop`
-> :warning: This rule is **deprecated** in favour of `squid:EmptyStatementUsageCheck`.
-
------
-
-An empty statement (aka a semicolon by itself) that is not used as the sole body of a for loop or while loop is probably a bug. It could also be a double semicolon, which is useless and should be removed.
diff --git a/docs/rules/EmptyStaticInitializer.md b/docs/rules/EmptyStaticInitializer.md
deleted file mode 100644
index f59cdef5..00000000
--- a/docs/rules/EmptyStaticInitializer.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# EmptyStaticInitializer
-**Category:** `pmd`
-**Rule Key:** `pmd:EmptyStaticInitializer`
-> :warning: This rule is **deprecated** in favour of [S00108](https://rules.sonarsource.com/java/RSPEC-108).
-
------
-
-An empty static initializer was found.
diff --git a/docs/rules/EmptySwitchStatements.md b/docs/rules/EmptySwitchStatements.md
deleted file mode 100644
index db2743cc..00000000
--- a/docs/rules/EmptySwitchStatements.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# EmptySwitchStatements
-**Category:** `pmd`
-**Rule Key:** `pmd:EmptySwitchStatements`
-> :warning: This rule is **deprecated** in favour of [S00108](https://rules.sonarsource.com/java/RSPEC-108).
-
------
-
-Avoid empty switch statements.
diff --git a/docs/rules/EmptySynchronizedBlock.md b/docs/rules/EmptySynchronizedBlock.md
deleted file mode 100644
index 213e03c7..00000000
--- a/docs/rules/EmptySynchronizedBlock.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# EmptySynchronizedBlock
-**Category:** `pmd`
-**Rule Key:** `pmd:EmptySynchronizedBlock`
-> :warning: This rule is **deprecated** in favour of [S00108](https://rules.sonarsource.com/java/RSPEC-108).
-
------
-
-Avoid empty synchronized blocks - they're useless.
diff --git a/docs/rules/EmptyTryBlock.md b/docs/rules/EmptyTryBlock.md
deleted file mode 100644
index 8e8edee1..00000000
--- a/docs/rules/EmptyTryBlock.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# EmptyTryBlock
-**Category:** `pmd`
-**Rule Key:** `pmd:EmptyTryBlock`
-> :warning: This rule is **deprecated** in favour of [S00108](https://rules.sonarsource.com/java/RSPEC-108).
-
------
-
-Avoid empty try blocks - what's the point?
diff --git a/docs/rules/EmptyWhileStmt.md b/docs/rules/EmptyWhileStmt.md
deleted file mode 100644
index a6b5b517..00000000
--- a/docs/rules/EmptyWhileStmt.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# EmptyWhileStmt
-**Category:** `pmd`
-**Rule Key:** `pmd:EmptyWhileStmt`
-> :warning: This rule is **deprecated** in favour of [S00108](https://rules.sonarsource.com/java/RSPEC-108).
-
------
-
-Empty While Statement finds all instances where a while statement does nothing. If it is a timing loop, then you should use Thread.sleep() for it; if it's a while loop that does a lot in the exit expression, rewrite it to make it clearer.
diff --git a/docs/rules/EqualsNull.md b/docs/rules/EqualsNull.md
deleted file mode 100644
index 212f52b8..00000000
--- a/docs/rules/EqualsNull.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# EqualsNull
-**Category:** `pmd`
-**Rule Key:** `pmd:EqualsNull`
-> :warning: This rule is **deprecated** in favour of [S2159](https://rules.sonarsource.com/java/RSPEC-2159).
-
------
-
-Inexperienced programmers sometimes confuse comparison concepts and use equals() to compare to null.
diff --git a/docs/rules/ExceptionAsFlowControl.md b/docs/rules/ExceptionAsFlowControl.md
deleted file mode 100644
index 1306ea13..00000000
--- a/docs/rules/ExceptionAsFlowControl.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# ExceptionAsFlowControl
-**Category:** `pmd`
-**Rule Key:** `pmd:ExceptionAsFlowControl`
-> :warning: This rule is **deprecated** in favour of [S1141](https://rules.sonarsource.com/java/RSPEC-1141).
-
------
-
-Using Exceptions as flow control leads to GOTOish code and obscures true exceptions when debugging.
diff --git a/docs/rules/ExcessiveClassLength.md b/docs/rules/ExcessiveClassLength.md
deleted file mode 100644
index 4b971ee2..00000000
--- a/docs/rules/ExcessiveClassLength.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# ExcessiveClassLength
-**Category:** `pmd`
-**Rule Key:** `pmd:ExcessiveClassLength`
-> :warning: This rule is **deprecated** in favour of [S1448](https://rules.sonarsource.com/java/RSPEC-1448).
-
------
-
-Long Class files are indications that the class may be trying to do too much. Try to break it down, and reduce the size to something manageable.
diff --git a/docs/rules/ExcessiveImports.md b/docs/rules/ExcessiveImports.md
deleted file mode 100644
index 91956dec..00000000
--- a/docs/rules/ExcessiveImports.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# ExcessiveImports
-**Category:** `pmd`
-**Rule Key:** `pmd:ExcessiveImports`
-> :warning: This rule is **deprecated** in favour of [S1200](https://rules.sonarsource.com/java/RSPEC-1200).
-
------
-
-A high number of imports can indicate a high degree of coupling within an object. Rule counts the number of unique imports and reports a violation if the count is above the user defined threshold.
diff --git a/docs/rules/ExcessiveMethodLength.md b/docs/rules/ExcessiveMethodLength.md
deleted file mode 100644
index 979707c7..00000000
--- a/docs/rules/ExcessiveMethodLength.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# ExcessiveMethodLength
-**Category:** `pmd`
-**Rule Key:** `pmd:ExcessiveMethodLength`
-> :warning: This rule is **deprecated** in favour of [S138](https://rules.sonarsource.com/java/RSPEC-138).
-
------
-
-Violations of this rule usually indicate that the method is doing too much. Try to reduce the method size by creating helper methods and removing any copy/pasted code.
diff --git a/docs/rules/ExcessiveParameterList.md b/docs/rules/ExcessiveParameterList.md
deleted file mode 100644
index 7ac29cc5..00000000
--- a/docs/rules/ExcessiveParameterList.md
+++ /dev/null
@@ -1,11 +0,0 @@
-# ExcessiveParameterList
-**Category:** `pmd`
-**Rule Key:** `pmd:ExcessiveParameterList`
-> :warning: This rule is **deprecated** in favour of [S00107](https://rules.sonarsource.com/java/RSPEC-107).
-
------
-
-
-**Rule Key:** `pmd:ExcessivePublicCount`
-> :warning: This rule is **deprecated** in favour of [S1448](https://rules.sonarsource.com/java/RSPEC-1448).
-
------
-
-A large number of public methods and attributes declared in a class can indicate the class may need to be broken up as increased effort will be required to thoroughly test it.
diff --git a/docs/rules/ExtendsObject.md b/docs/rules/ExtendsObject.md
deleted file mode 100644
index 5ab0b143..00000000
--- a/docs/rules/ExtendsObject.md
+++ /dev/null
@@ -1,12 +0,0 @@
-# ExtendsObject
-**Category:** `pmd`
-**Rule Key:** `pmd:ExtendsObject`
-> :warning: This rule is **deprecated** in favour of [S1939](https://rules.sonarsource.com/java/RSPEC-1939).
-
------
-
-No need to explicitly extend Object. Example:
-
-public class Foo extends Object { // not required
-}
-
diff --git a/docs/rules/FieldDeclarationsShouldBeAtStartOfClass.md b/docs/rules/FieldDeclarationsShouldBeAtStartOfClass.md
deleted file mode 100644
index 3a5c0bdb..00000000
--- a/docs/rules/FieldDeclarationsShouldBeAtStartOfClass.md
+++ /dev/null
@@ -1,22 +0,0 @@
-# FieldDeclarationsShouldBeAtStartOfClass
-**Category:** `pmd`
-**Rule Key:** `pmd:FieldDeclarationsShouldBeAtStartOfClass`
-> :warning: This rule is **deprecated** in favour of [S1213](https://rules.sonarsource.com/java/RSPEC-1213).
-
------
-
-Fields should be declared at the top of the class, before any method declarations, constructors, initializers or inner classes. Example:
-
-public class HelloWorldBean {
-
- // Field declared before methods / inner classes - OK
- private String _thing;
-
- public String getMessage() {
- return "Hello World!";
- }
-
- // Field declared after methods / inner classes - avoid this
- private String _fieldInWrongLocation;
-}
-
diff --git a/docs/rules/FinalFieldCouldBeStatic.md b/docs/rules/FinalFieldCouldBeStatic.md
deleted file mode 100644
index 75af7276..00000000
--- a/docs/rules/FinalFieldCouldBeStatic.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# FinalFieldCouldBeStatic
-**Category:** `pmd`
-**Rule Key:** `pmd:FinalFieldCouldBeStatic`
-> :warning: This rule is **deprecated** in favour of [S1170](https://rules.sonarsource.com/java/RSPEC-1170).
-
------
-
-If a final field is assigned to a compile-time constant, it could be made static, thus saving overhead in each object at runtime.
diff --git a/docs/rules/FinalizeDoesNotCallSuperFinalize.md b/docs/rules/FinalizeDoesNotCallSuperFinalize.md
deleted file mode 100644
index e3c6bcb6..00000000
--- a/docs/rules/FinalizeDoesNotCallSuperFinalize.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# FinalizeDoesNotCallSuperFinalize
-**Category:** `pmd`
-**Rule Key:** `pmd:FinalizeDoesNotCallSuperFinalize`
-> :warning: This rule is **deprecated** in favour of `squid:ObjectFinalizeOverridenCallsSuperFinalizeCheck`.
-
------
-
-If the finalize() is implemented, its last action should be to call super.finalize.
diff --git a/docs/rules/FinalizeOnlyCallsSuperFinalize.md b/docs/rules/FinalizeOnlyCallsSuperFinalize.md
deleted file mode 100644
index cba91cbc..00000000
--- a/docs/rules/FinalizeOnlyCallsSuperFinalize.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# FinalizeOnlyCallsSuperFinalize
-**Category:** `pmd`
-**Rule Key:** `pmd:FinalizeOnlyCallsSuperFinalize`
-> :warning: This rule is **deprecated** in favour of [S1185](https://rules.sonarsource.com/java/RSPEC-1185).
-
------
-
-If the finalize() is implemented, it should do something besides just calling super.finalize().
diff --git a/docs/rules/FinalizeOverloaded.md b/docs/rules/FinalizeOverloaded.md
deleted file mode 100644
index 511b9b19..00000000
--- a/docs/rules/FinalizeOverloaded.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# FinalizeOverloaded
-**Category:** `pmd`
-**Rule Key:** `pmd:FinalizeOverloaded`
-> :warning: This rule is **deprecated** in favour of [S1175](https://rules.sonarsource.com/java/RSPEC-1175).
-
------
-
-Methods named finalize() should not have parameters. It is confusing and probably a bug to overload finalize(). It will not be called by the VM.
diff --git a/docs/rules/FinalizeShouldBeProtected.md b/docs/rules/FinalizeShouldBeProtected.md
deleted file mode 100644
index fbf546e7..00000000
--- a/docs/rules/FinalizeShouldBeProtected.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# FinalizeShouldBeProtected
-**Category:** `pmd`
-**Rule Key:** `pmd:FinalizeShouldBeProtected`
-> :warning: This rule is **deprecated** in favour of [S1174](https://rules.sonarsource.com/java/RSPEC-1174).
-
------
-
-If you override finalize(), make it protected. If you make it public, other classes may call it.
diff --git a/docs/rules/ForLoopShouldBeWhileLoop.md b/docs/rules/ForLoopShouldBeWhileLoop.md
deleted file mode 100644
index 22f339a5..00000000
--- a/docs/rules/ForLoopShouldBeWhileLoop.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# ForLoopShouldBeWhileLoop
-**Category:** `pmd`
-**Rule Key:** `pmd:ForLoopShouldBeWhileLoop`
-> :warning: This rule is **deprecated** in favour of [S1264](https://rules.sonarsource.com/java/RSPEC-1264).
-
------
-
-Some for loops can be simplified to while loops - this makes them more concise.
diff --git a/docs/rules/ForLoopsMustUseBraces.md b/docs/rules/ForLoopsMustUseBraces.md
deleted file mode 100644
index bedecff3..00000000
--- a/docs/rules/ForLoopsMustUseBraces.md
+++ /dev/null
@@ -1,10 +0,0 @@
-# ForLoopsMustUseBraces
-**Category:** `pmd`
-**Rule Key:** `pmd:ForLoopsMustUseBraces`
-> :warning: This rule is **deprecated** in favour of [S00121](https://rules.sonarsource.com/java/RSPEC-121).
-
------
-
-for (int i=0; i<42;i++) foo();
-
-**Rule Key:** `pmd:GenericsNaming`
-> :warning: This rule is **deprecated** in favour of [S00119](https://rules.sonarsource.com/java/RSPEC-119).
-
------
-
-Generics names should be a one letter long and upper case.
diff --git a/docs/rules/GodClass.md b/docs/rules/GodClass.md
deleted file mode 100644
index a68af8f2..00000000
--- a/docs/rules/GodClass.md
+++ /dev/null
@@ -1,14 +0,0 @@
-# GodClass
-**Category:** `pmd`
-**Rule Key:** `pmd:GodClass`
-
-
------
-
-The God Class rule detects the God Class design flaw using metrics. God classes do too many things,
-are very big and overly complex. They should be split apart to be more object-oriented.
-The rule uses the detection strategy described in "Object-Oriented Metrics in Practice".
-The violations are reported against the entire class. See also the references:
-Michele Lanza and Radu Marinescu. Object-Oriented Metrics in Practice:
-Using Software Metrics to Characterize, Evaluate, and Improve the Design
-of Object-Oriented Systems. Springer, Berlin, 1 edition, October 2006. Page 80.
diff --git a/docs/rules/GuardDebugLogging.md b/docs/rules/GuardDebugLogging.md
deleted file mode 100644
index 1a345af2..00000000
--- a/docs/rules/GuardDebugLogging.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# GuardDebugLogging
-**Category:** `pmd`
-**Rule Key:** `pmd:GuardDebugLogging`
-
-
------
-
-When log messages are composed by concatenating strings, the whole section should be guarded by a isDebugEnabled() check to avoid performance and memory issues.
diff --git a/docs/rules/GuardLogStatement.md b/docs/rules/GuardLogStatement.md
deleted file mode 100644
index 23859d67..00000000
--- a/docs/rules/GuardLogStatement.md
+++ /dev/null
@@ -1,14 +0,0 @@
-# GuardLogStatement
-**Category:** `pmd`
-**Rule Key:** `pmd:GuardLogStatement`
-
-
------
-
-Whenever using a log level, one should check if the loglevel is actually enabled, or
-otherwise skip the associate String creation and manipulation. Example:
-
-// Add this for performance
-if (log.isDebugEnabled() { ...
- log.debug("This happens");
-
diff --git a/docs/rules/GuardLogStatementJavaUtil.md b/docs/rules/GuardLogStatementJavaUtil.md
deleted file mode 100644
index 76c2f87a..00000000
--- a/docs/rules/GuardLogStatementJavaUtil.md
+++ /dev/null
@@ -1,14 +0,0 @@
-# GuardLogStatementJavaUtil
-**Category:** `pmd`
-**Rule Key:** `pmd:GuardLogStatementJavaUtil`
-
-
------
-
-Whenever using a log level, one should check if the loglevel is actually enabled, or
-otherwise skip the associate String creation and manipulation. Example:
-
-// Add this for performance
-if (log.isLoggable(Level.FINE)) { ...
- log.fine("This happens");
-
diff --git a/docs/rules/IdempotentOperations.md b/docs/rules/IdempotentOperations.md
deleted file mode 100644
index 0fd1ec32..00000000
--- a/docs/rules/IdempotentOperations.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# IdempotentOperations
-**Category:** `pmd`
-**Rule Key:** `pmd:IdempotentOperations`
-> :warning: This rule is **deprecated** in favour of [S1656](https://rules.sonarsource.com/java/RSPEC-1656).
-
------
-
-Avoid idempotent operations - they are have no effect. Example : int x = 2;
diff --git a/docs/rules/IfElseStmtsMustUseBraces.md b/docs/rules/IfElseStmtsMustUseBraces.md
deleted file mode 100644
index 6601cd73..00000000
--- a/docs/rules/IfElseStmtsMustUseBraces.md
+++ /dev/null
@@ -1,10 +0,0 @@
-# IfElseStmtsMustUseBraces
-**Category:** `pmd`
x = x;
-**Rule Key:** `pmd:IfElseStmtsMustUseBraces`
-> :warning: This rule is **deprecated** in favour of [S00121](https://rules.sonarsource.com/java/RSPEC-121).
-
------
-
-
-**Rule Key:** `pmd:IfStmtsMustUseBraces`
-> :warning: This rule is **deprecated** in favour of [S00121](https://rules.sonarsource.com/java/RSPEC-121).
-
------
-
-
-**Rule Key:** `pmd:ImmutableField`
-
-
------
-
-Identifies private fields whose values never change once they are initialized either in the declaration of the field or by a constructor. This aids in converting existing classes to immutable classes.
diff --git a/docs/rules/ImportFromSamePackage.md b/docs/rules/ImportFromSamePackage.md
deleted file mode 100644
index ebe2ac8f..00000000
--- a/docs/rules/ImportFromSamePackage.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# ImportFromSamePackage
-**Category:** `pmd`
-**Rule Key:** `pmd:ImportFromSamePackage`
-> :warning: This rule is **deprecated** in favour of `squid:UselessImportCheck`.
-
------
-
-No need to import a type that lives in the same package.
diff --git a/docs/rules/InefficientEmptyStringCheck.md b/docs/rules/InefficientEmptyStringCheck.md
deleted file mode 100644
index e1af7eb9..00000000
--- a/docs/rules/InefficientEmptyStringCheck.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# InefficientEmptyStringCheck
-**Category:** `pmd`
-**Rule Key:** `pmd:InefficientEmptyStringCheck`
-
-
------
-
-String.trim().length() is an inefficient way to check if a String is really empty, as it creates a new String object just to check its size. Consider creating a static function that loops through a string, checking Character.isWhitespace() on each character and returning false if a non-whitespace character is found.
diff --git a/docs/rules/InefficientStringBuffering.md b/docs/rules/InefficientStringBuffering.md
deleted file mode 100644
index 60d9dbcc..00000000
--- a/docs/rules/InefficientStringBuffering.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# InefficientStringBuffering
-**Category:** `pmd`
-**Rule Key:** `pmd:InefficientStringBuffering`
-
-
------
-
-Avoid concatenating non literals in a StringBuffer constructor or append().
diff --git a/docs/rules/InstantiationToGetClass.md b/docs/rules/InstantiationToGetClass.md
deleted file mode 100644
index e8370bf0..00000000
--- a/docs/rules/InstantiationToGetClass.md
+++ /dev/null
@@ -1,9 +0,0 @@
-# InstantiationToGetClass
-**Category:** `pmd`
-**Rule Key:** `pmd:InstantiationToGetClass`
-> :warning: This rule is **deprecated** in favour of [S2133](https://rules.sonarsource.com/java/RSPEC-2133).
-
------
-
-Avoid instantiating an object just to call getClass() on it; use the .class public member instead. Example : replace
-Class c = new String().getClass();
with Class c = String.class;
diff --git a/docs/rules/InsufficientStringBufferDeclaration.md b/docs/rules/InsufficientStringBufferDeclaration.md
deleted file mode 100644
index e82e416a..00000000
--- a/docs/rules/InsufficientStringBufferDeclaration.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# InsufficientStringBufferDeclaration
-**Category:** `pmd`
-**Rule Key:** `pmd:InsufficientStringBufferDeclaration`
-
-
------
-
-Failing to pre-size a StringBuffer properly could cause it to re-size many times during runtime. This rule checks the characters that are actually passed into StringBuffer.append(), but represents a best guess worst case scenario. An empty StringBuffer constructor initializes the object to 16 characters. This default is assumed if the length of the constructor can not be determined.
diff --git a/docs/rules/IntegerInstantiation.md b/docs/rules/IntegerInstantiation.md
deleted file mode 100644
index a3e46720..00000000
--- a/docs/rules/IntegerInstantiation.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# IntegerInstantiation
-**Category:** `pmd`
-**Rule Key:** `pmd:IntegerInstantiation`
-
-
------
-
-In JDK 1.5, calling new Integer() causes memory allocation. Integer.valueOf() is more memory friendly.
diff --git a/docs/rules/JUnit4SuitesShouldUseSuiteAnnotation.md b/docs/rules/JUnit4SuitesShouldUseSuiteAnnotation.md
deleted file mode 100644
index 299fece8..00000000
--- a/docs/rules/JUnit4SuitesShouldUseSuiteAnnotation.md
+++ /dev/null
@@ -1,22 +0,0 @@
-# JUnit4SuitesShouldUseSuiteAnnotation
-**Category:** `pmd-unit-tests`
-**Rule Key:** `pmd-unit-tests:JUnit4SuitesShouldUseSuiteAnnotation`
-
-
------
-
-In JUnit 3, test suites are indicated by the suite() method. In JUnit 4, suites are indicated
-through the @RunWith(Suite.class) annotation. Example:
-
-public class BadExample extends TestCase{
-
- public static Test suite(){
- return new Suite();
- }
-}
-
-@RunWith(Suite.class)
-@SuiteClasses( { TestOne.class, TestTwo.class })
-public class GoodTest {
-}
-
diff --git a/docs/rules/JUnit4TestShouldUseAfterAnnotation.md b/docs/rules/JUnit4TestShouldUseAfterAnnotation.md
deleted file mode 100644
index b91ef788..00000000
--- a/docs/rules/JUnit4TestShouldUseAfterAnnotation.md
+++ /dev/null
@@ -1,21 +0,0 @@
-# JUnit4TestShouldUseAfterAnnotation
-**Category:** `pmd-unit-tests`
-**Rule Key:** `pmd-unit-tests:JUnit4TestShouldUseAfterAnnotation`
-
-
------
-
-In JUnit 3, the tearDown method was used to clean up all data entities required in running tests.
-JUnit 4 skips the tearDown method and executes all methods annotated with @After after running each test Example:
-
-public class MyTest {
- public void tearDown() {
- bad();
- }
-}
-public class MyTest2 {
- @After public void tearDown() {
- good();
- }
-}
-
diff --git a/docs/rules/JUnit4TestShouldUseBeforeAnnotation.md b/docs/rules/JUnit4TestShouldUseBeforeAnnotation.md
deleted file mode 100644
index ab8409c0..00000000
--- a/docs/rules/JUnit4TestShouldUseBeforeAnnotation.md
+++ /dev/null
@@ -1,21 +0,0 @@
-# JUnit4TestShouldUseBeforeAnnotation
-**Category:** `pmd-unit-tests`
-**Rule Key:** `pmd-unit-tests:JUnit4TestShouldUseBeforeAnnotation`
-
-
------
-
-In JUnit 3, the setUp method was used to set up all data entities required in running tests.
-JUnit 4 skips the setUp method and executes all methods annotated with @Before before all tests Example:
-
-public class MyTest {
- public void setUp() {
- bad();
- }
-}
-public class MyTest2 {
- @Before public void setUp() {
- good();
- }
-}
-
diff --git a/docs/rules/JUnit4TestShouldUseTestAnnotation.md b/docs/rules/JUnit4TestShouldUseTestAnnotation.md
deleted file mode 100644
index 87f04700..00000000
--- a/docs/rules/JUnit4TestShouldUseTestAnnotation.md
+++ /dev/null
@@ -1,21 +0,0 @@
-# JUnit4TestShouldUseTestAnnotation
-**Category:** `pmd-unit-tests`
-**Rule Key:** `pmd-unit-tests:JUnit4TestShouldUseTestAnnotation`
-
-
------
-
-In JUnit 3, the framework executed all methods which started with the word test as a unit test.
-In JUnit 4, only methods annotated with the @Test annotation are executed. Example:
-
-public class MyTest {
- public void testBad() {
- doSomething();
- }
-
- @Test
- public void testGood() {
- doSomething();
- }
-}
-
diff --git a/docs/rules/JUnitAssertionsShouldIncludeMessage.md b/docs/rules/JUnitAssertionsShouldIncludeMessage.md
deleted file mode 100644
index c1cdd0cf..00000000
--- a/docs/rules/JUnitAssertionsShouldIncludeMessage.md
+++ /dev/null
@@ -1,15 +0,0 @@
-# JUnitAssertionsShouldIncludeMessage
-**Category:** `pmd-unit-tests`
-**Rule Key:** `pmd-unit-tests:JUnitAssertionsShouldIncludeMessage`
-> :warning: This rule is **deprecated** in favour of [S2698](https://rules.sonarsource.com/java/RSPEC-2698).
-
------
-
-JUnit assertions should include a message - i.e., use the three argument version of assertEquals(), not the two argument version.
-
-public class Foo extends TestCase {
- public void testSomething() {
- assertEquals("foo", "bar"); // violation, should be assertEquals("Foo does not equals bar", "foo", "bar");
- }
-}
-
diff --git a/docs/rules/JUnitSpelling.md b/docs/rules/JUnitSpelling.md
deleted file mode 100644
index 65f330f5..00000000
--- a/docs/rules/JUnitSpelling.md
+++ /dev/null
@@ -1,16 +0,0 @@
-# JUnitSpelling
-**Category:** `pmd-unit-tests`
-**Rule Key:** `pmd-unit-tests:JUnitSpelling`
-
-
------
-
-Some JUnit framework methods are easy to misspell.
-
-import junit.framework.*;
-
-public class Foo extends TestCase {
- public void setup() {} // violation, should be setUp()
- public void TearDown() {} // violation, should be tearDown()
-}
-
diff --git a/docs/rules/JUnitStaticSuite.md b/docs/rules/JUnitStaticSuite.md
deleted file mode 100644
index b0d3640d..00000000
--- a/docs/rules/JUnitStaticSuite.md
+++ /dev/null
@@ -1,16 +0,0 @@
-# JUnitStaticSuite
-**Category:** `pmd-unit-tests`
-**Rule Key:** `pmd-unit-tests:JUnitStaticSuite`
-
-
------
-
-The suite() method in a JUnit test needs to be both public and static.
-
-import junit.framework.*;
-
-public class Foo extends TestCase {
- public void suite() {} // violation, should be static
- private static void suite() {} // violation, should be public
-}
-
diff --git a/docs/rules/JUnitTestContainsTooManyAsserts.md b/docs/rules/JUnitTestContainsTooManyAsserts.md
deleted file mode 100644
index 00dee06f..00000000
--- a/docs/rules/JUnitTestContainsTooManyAsserts.md
+++ /dev/null
@@ -1,26 +0,0 @@
-# JUnitTestContainsTooManyAsserts
-**Category:** `pmd-unit-tests`
-**Rule Key:** `pmd-unit-tests:JUnitTestContainsTooManyAsserts`
-
-
------
-
-JUnit tests should not contain too many asserts. Many asserts are indicative of a complex test, for which
-it is harder to verify correctness. Consider breaking the test scenario into multiple, shorter test scenarios.
-Customize the maximum number of assertions used by this Rule to suit your needs. Example:
-
-public class MyTestCase extends TestCase {
- // Ok
- public void testMyCaseWithOneAssert() {
- boolean myVar = false;
- assertFalse("should be false", myVar);
- }
-
- // Bad, too many asserts (assuming max=1)
- public void testMyCaseWithMoreAsserts() {
- boolean myVar = false;
- assertFalse("myVar should be false", myVar);
- assertEquals("should equals false", false, myVar);
- }
-}
-
diff --git a/docs/rules/JUnitTestsShouldIncludeAssert.md b/docs/rules/JUnitTestsShouldIncludeAssert.md
deleted file mode 100644
index e6e5c223..00000000
--- a/docs/rules/JUnitTestsShouldIncludeAssert.md
+++ /dev/null
@@ -1,17 +0,0 @@
-# JUnitTestsShouldIncludeAssert
-**Category:** `pmd-unit-tests`
-**Rule Key:** `pmd-unit-tests:JUnitTestsShouldIncludeAssert`
-
-
------
-
-JUnit tests should include at least one assertion. This makes the tests more robust, and using assert with messages provide the developer a clearer idea of what the test does.
-
-public class Foo extends TestCase {
- public void testSomething() {
- Bar b = findBar();
- b.work();
- // violation, we could use assertNotNull("bar not found", b);
- }
-}
-
diff --git a/docs/rules/JUnitUseExpected.md b/docs/rules/JUnitUseExpected.md
deleted file mode 100644
index 0117f897..00000000
--- a/docs/rules/JUnitUseExpected.md
+++ /dev/null
@@ -1,25 +0,0 @@
-# JUnitUseExpected
-**Category:** `pmd-unit-tests`
-**Rule Key:** `pmd-unit-tests:JUnitUseExpected`
-
-
------
-
-In JUnit4, use the @Test(expected) annotation to denote tests that should throw exceptions. Example:
-
-public class MyTest {
- @Test
- public void testBad() {
- try {
- doSomething();
- fail("should have thrown an exception");
- } catch (Exception e) {
- }
- }
-
- @Test(expected=Exception.class)
- public void testGood() {
- doSomething();
- }
-}
-
diff --git a/docs/rules/JumbledIncrementer.md b/docs/rules/JumbledIncrementer.md
deleted file mode 100644
index 23608eaa..00000000
--- a/docs/rules/JumbledIncrementer.md
+++ /dev/null
@@ -1,19 +0,0 @@
-# JumbledIncrementer
-**Category:** `pmd`
-**Rule Key:** `pmd:JumbledIncrementer`
-> :warning: This rule is **deprecated** in favour of `squid:ForLoopCounterChangedCheck`.
-
------
-
-Avoid jumbled loop incrementers - it's usually a mistake, and it's confusing even if it's what's intended.
-
Example :
-
-public class JumbledIncrementerRule1 {
- public void foo() {
- for (int i = 0; i < 10; i++) {
- for (int k = 0; k < 20; i++) {
- System.out.println("Hello");
- }
- }
- }
-}
diff --git a/docs/rules/LawOfDemeter.md b/docs/rules/LawOfDemeter.md
deleted file mode 100644
index 479cca5b..00000000
--- a/docs/rules/LawOfDemeter.md
+++ /dev/null
@@ -1,37 +0,0 @@
-# LawOfDemeter
-**Category:** `pmd`
-**Rule Key:** `pmd:LawOfDemeter`
-
-
------
-
-The Law of Demeter is a simple rule, that says "only talk to friends". It helps to reduce coupling between classes or objects.
-See also the references:
-Andrew Hunt, David Thomas, and Ward Cunningham. The Pragmatic Programmer. From Journeyman to Master. Addison-Wesley Longman, Amsterdam, October 1999.;
-K.J. Lieberherr and I.M. Holland. Assuring good style for object-oriented programs. Software, IEEE, 6(5):38–48, 1989.;
-http://www.ccs.neu.edu/home/lieber/LoD.html;
-http://en.wikipedia.org/wiki/Law_of_Demeter
-
-public class Foo {
- /**
- * This example will result in two violations.
- */
- public void example(Bar b) {
- // this method call is ok, as b is a parameter of "example"
- C c = b.getC();
-
- // this method call is a violation, as we are using c, which we got from B.
- // We should ask b directly instead, e.g. "b.doItOnC();"
- c.doIt();
-
- // this is also a violation, just expressed differently as a method chain without temporary variables.
- b.getC().doIt();
-
- // a constructor call, not a method call.
- D d = new D();
- // this method call is ok, because we have create the new instance of D locally.
- d.doSomethingElse();
- }
-}
-
diff --git a/docs/rules/LocalHomeNamingConvention.md b/docs/rules/LocalHomeNamingConvention.md
deleted file mode 100644
index 87b0fe65..00000000
--- a/docs/rules/LocalHomeNamingConvention.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# LocalHomeNamingConvention
-**Category:** `pmd`
-**Rule Key:** `pmd:LocalHomeNamingConvention`
-
-
------
-
-The Local Home interface of a Session EJB should be suffixed by "LocalHome".
diff --git a/docs/rules/LocalInterfaceSessionNamingConvention.md b/docs/rules/LocalInterfaceSessionNamingConvention.md
deleted file mode 100644
index f156dd5e..00000000
--- a/docs/rules/LocalInterfaceSessionNamingConvention.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# LocalInterfaceSessionNamingConvention
-**Category:** `pmd`
-**Rule Key:** `pmd:LocalInterfaceSessionNamingConvention`
-
-
------
-
-The Local Interface of a Session EJB should be suffixed by "Local".
diff --git a/docs/rules/LocalVariableCouldBeFinal.md b/docs/rules/LocalVariableCouldBeFinal.md
deleted file mode 100644
index 7cffcb76..00000000
--- a/docs/rules/LocalVariableCouldBeFinal.md
+++ /dev/null
@@ -1,16 +0,0 @@
-# LocalVariableCouldBeFinal
-**Category:** `pmd`
-**Rule Key:** `pmd:LocalVariableCouldBeFinal`
-
-
------
-
-A local variable assigned only once can be declared final. Example :
-
-public class Bar {
- public void foo () {
- String a = "a"; //if a will not be assigned again it is better to do this:
- final String b = "b";
- }
-}
-
diff --git a/docs/rules/LoggerIsNotStaticFinal.md b/docs/rules/LoggerIsNotStaticFinal.md
deleted file mode 100644
index 3862ca6c..00000000
--- a/docs/rules/LoggerIsNotStaticFinal.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# LoggerIsNotStaticFinal
-**Category:** `pmd`
-**Rule Key:** `pmd:LoggerIsNotStaticFinal`
-> :warning: This rule is **deprecated** in favour of [S1312](https://rules.sonarsource.com/java/RSPEC-1312).
-
------
-
-In most cases, the Logger can be declared static and final.
diff --git a/docs/rules/LogicInversion.md b/docs/rules/LogicInversion.md
deleted file mode 100644
index 5139c034..00000000
--- a/docs/rules/LogicInversion.md
+++ /dev/null
@@ -1,20 +0,0 @@
-# LogicInversion
-**Category:** `pmd`
-**Rule Key:** `pmd:LogicInversion`
-> :warning: This rule is **deprecated** in favour of [S1940](https://rules.sonarsource.com/java/RSPEC-1940).
-
------
-
-Use opposite operator instead of negating the whole expression with a logic complement operator. Example:
-
-public boolean bar(int a, int b) {
-
- if (!(a == b)) // use !=
- return false;
-
- if (!(a < b)) // use >=
- return false;
-
- return true;
-}
-
diff --git a/docs/rules/LongInstantiation.md b/docs/rules/LongInstantiation.md
deleted file mode 100644
index 91cb0abc..00000000
--- a/docs/rules/LongInstantiation.md
+++ /dev/null
@@ -1,14 +0,0 @@
-# LongInstantiation
-**Category:** `pmd`
-**Rule Key:** `pmd:LongInstantiation`
-
-
------
-
-In JDK 1.5, calling new Long() causes memory allocation. Long.valueOf() is more memory friendly. Example :
-
-public class Foo {
-private Long i = new Long(0); // change to Long i =
-Long.valueOf(0);
-}
-
diff --git a/docs/rules/LongVariable.md b/docs/rules/LongVariable.md
deleted file mode 100644
index 0e9cb34b..00000000
--- a/docs/rules/LongVariable.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# LongVariable
-**Category:** `pmd`
-**Rule Key:** `pmd:LongVariable`
-> :warning: This rule is **deprecated** in favour of [S00117](https://rules.sonarsource.com/java/RSPEC-117).
-
------
-
-Detects when a field, formal or local variable is declared with a long name.
diff --git a/docs/rules/LooseCoupling.md b/docs/rules/LooseCoupling.md
deleted file mode 100644
index dac50e36..00000000
--- a/docs/rules/LooseCoupling.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# LooseCoupling
-**Category:** `pmd`
-**Rule Key:** `pmd:LooseCoupling`
-> :warning: This rule is **deprecated** in favour of [S1319](https://rules.sonarsource.com/java/RSPEC-1319).
-
------
-
-Avoid using implementation types (i.e., HashSet); use the interface (i.e, Set) instead
diff --git a/docs/rules/LooseCouplingWithTypeResolution.md b/docs/rules/LooseCouplingWithTypeResolution.md
deleted file mode 100644
index adad9ed1..00000000
--- a/docs/rules/LooseCouplingWithTypeResolution.md
+++ /dev/null
@@ -1,23 +0,0 @@
-# LooseCouplingWithTypeResolution
-**Category:** `pmd`
-**Rule Key:** `pmd:LooseCouplingWithTypeResolution`
-> :warning: This rule is **deprecated** in favour of [S1319](https://rules.sonarsource.com/java/RSPEC-1319).
-
------
-
-Avoid using implementation types (i.e., HashSet); use the interface (i.e, Set) instead Example:
-
-import java.util.ArrayList;
-import java.util.HashSet;
-
-public class Bar {
-
- // Use List instead
- private ArrayList list = new ArrayList();
-
- // Use Set instead
- public HashSet getFoo() {
- return new HashSet();
- }
-}
-
diff --git a/docs/rules/LoosePackageCoupling.md b/docs/rules/LoosePackageCoupling.md
deleted file mode 100644
index bcc596d1..00000000
--- a/docs/rules/LoosePackageCoupling.md
+++ /dev/null
@@ -1,18 +0,0 @@
-# LoosePackageCoupling
-**Category:** `pmd`
-**Rule Key:** `pmd:LoosePackageCoupling`
-> :warning: This rule is **deprecated** in favour of `squid:ArchitecturalConstraint`.
-
------
-
-Avoid using classes from the configured package hierarchy outside of the package hierarchy,
-except when using one of the configured allowed classes. Example:
-
-package some.package;
-
-import some.other.package.subpackage.subsubpackage.DontUseThisClass;
-
-public class Bar {
- DontUseThisClass boo = new DontUseThisClass();
-}
-
diff --git a/docs/rules/MDBAndSessionBeanNamingConvention.md b/docs/rules/MDBAndSessionBeanNamingConvention.md
deleted file mode 100644
index ff779af4..00000000
--- a/docs/rules/MDBAndSessionBeanNamingConvention.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# MDBAndSessionBeanNamingConvention
-**Category:** `pmd`
-**Rule Key:** `pmd:MDBAndSessionBeanNamingConvention`
-
-
------
-
-The EJB Specification state that any MessageDrivenBean or SessionBean should be suffixed by Bean.
diff --git a/docs/rules/MethodArgumentCouldBeFinal.md b/docs/rules/MethodArgumentCouldBeFinal.md
deleted file mode 100644
index 55d0369c..00000000
--- a/docs/rules/MethodArgumentCouldBeFinal.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# MethodArgumentCouldBeFinal
-**Category:** `pmd`
-**Rule Key:** `pmd:MethodArgumentCouldBeFinal`
-> :warning: This rule is **deprecated** in favour of [S1226](https://rules.sonarsource.com/java/RSPEC-1226).
-
------
-
-A method argument that is never assigned can be declared final.
diff --git a/docs/rules/MethodNamingConventions.md b/docs/rules/MethodNamingConventions.md
deleted file mode 100644
index 8418c2e0..00000000
--- a/docs/rules/MethodNamingConventions.md
+++ /dev/null
@@ -1,14 +0,0 @@
-# MethodNamingConventions
-**Category:** `pmd`
-**Rule Key:** `pmd:MethodNamingConventions`
-> :warning: This rule is **deprecated** in favour of [S00100](https://rules.sonarsource.com/java/RSPEC-100).
-
------
-
-Method names should always begin with a lower case character, and should not contain underscores. Example :
-
-public class Foo {
- public void fooStuff() {
- }
-}
-
diff --git a/docs/rules/MethodReturnsInternalArray.md b/docs/rules/MethodReturnsInternalArray.md
deleted file mode 100644
index 36e2d27d..00000000
--- a/docs/rules/MethodReturnsInternalArray.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# MethodReturnsInternalArray
-**Category:** `pmd`
-**Rule Key:** `pmd:MethodReturnsInternalArray`
-> :warning: This rule is **deprecated** in favour of [S2384](https://rules.sonarsource.com/java/RSPEC-2384).
-
------
-
-Exposing internal arrays directly allows the user to modify some code that could be critical. It is safer to return a copy of the array.
diff --git a/docs/rules/MethodWithSameNameAsEnclosingClass.md b/docs/rules/MethodWithSameNameAsEnclosingClass.md
deleted file mode 100644
index b1bdbe21..00000000
--- a/docs/rules/MethodWithSameNameAsEnclosingClass.md
+++ /dev/null
@@ -1,16 +0,0 @@
-# MethodWithSameNameAsEnclosingClass
-**Category:** `pmd`
-**Rule Key:** `pmd:MethodWithSameNameAsEnclosingClass`
-> :warning: This rule is **deprecated** in favour of [S1223](https://rules.sonarsource.com/java/RSPEC-1223).
-
------
-
-Non-constructor methods should not have the same name as the enclosing class. Example :
-
-public class MyClass {
- // this is bad because it is a method
- public void MyClass() {}
- // this is OK because it is a constructor
- public MyClass() {}
-}
-
diff --git a/docs/rules/MisleadingVariableName.md b/docs/rules/MisleadingVariableName.md
deleted file mode 100644
index 566176df..00000000
--- a/docs/rules/MisleadingVariableName.md
+++ /dev/null
@@ -1,16 +0,0 @@
-# MisleadingVariableName
-**Category:** `pmd`
-**Rule Key:** `pmd:MisleadingVariableName`
-> :warning: This rule is **deprecated** in favour of [S00117](https://rules.sonarsource.com/java/RSPEC-117).
-
------
-
-Detects when a non-field has a name starting with 'm_'. This usually indicates a field and thus is confusing. Example :
-
-public class Foo {
- private int m_foo; // OK
- public void bar(String m_baz) { // Bad
- int m_boz = 42; // Bad
- }
-}
-
diff --git a/docs/rules/MisplacedNullCheck.md b/docs/rules/MisplacedNullCheck.md
deleted file mode 100644
index 431089c2..00000000
--- a/docs/rules/MisplacedNullCheck.md
+++ /dev/null
@@ -1,15 +0,0 @@
-# MisplacedNullCheck
-**Category:** `pmd`
-**Rule Key:** `pmd:MisplacedNullCheck`
-> :warning: This rule is **deprecated** in favour of [S1697](https://rules.sonarsource.com/java/RSPEC-1697), [S2259](https://rules.sonarsource.com/java/RSPEC-2259).
-
------
-
-The null check here is misplaced. if the variable is null you'll get a NullPointerException.
-Either the check is useless (the variable will never be null) or it's incorrect.
-
Example :
-
-if (object1!=null && object2.equals(object1)) {
- ...
-}
-
diff --git a/docs/rules/MissingBreakInSwitch.md b/docs/rules/MissingBreakInSwitch.md
deleted file mode 100644
index eaabeb4c..00000000
--- a/docs/rules/MissingBreakInSwitch.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# MissingBreakInSwitch
-**Category:** `pmd`
-**Rule Key:** `pmd:MissingBreakInSwitch`
-> :warning: This rule is **deprecated** in favour of [S128](https://rules.sonarsource.com/java/RSPEC-128).
-
------
-
-A switch statement without an enclosed break statement may be a bug.
diff --git a/docs/rules/MissingSerialVersionUID.md b/docs/rules/MissingSerialVersionUID.md
deleted file mode 100644
index d19cf20d..00000000
--- a/docs/rules/MissingSerialVersionUID.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# MissingSerialVersionUID
-**Category:** `pmd`
-**Rule Key:** `pmd:MissingSerialVersionUID`
-> :warning: This rule is **deprecated** in favour of [S2057](https://rules.sonarsource.com/java/RSPEC-2057).
-
------
-
-Classes that are serializable should provide a serialVersionUID field.
diff --git a/docs/rules/MissingStaticMethodInNonInstantiatableClass.md b/docs/rules/MissingStaticMethodInNonInstantiatableClass.md
deleted file mode 100644
index 5c704a11..00000000
--- a/docs/rules/MissingStaticMethodInNonInstantiatableClass.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# MissingStaticMethodInNonInstantiatableClass
-**Category:** `pmd`
-**Rule Key:** `pmd:MissingStaticMethodInNonInstantiatableClass`
-
-
------
-
-A class that has private constructors and does not have any static methods or fields cannot be used.
diff --git a/docs/rules/ModifiedCyclomaticComplexity.md b/docs/rules/ModifiedCyclomaticComplexity.md
deleted file mode 100644
index 59c14234..00000000
--- a/docs/rules/ModifiedCyclomaticComplexity.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# ModifiedCyclomaticComplexity
-**Category:** `pmd`
-**Rule Key:** `pmd:ModifiedCyclomaticComplexity`
-> :warning: This rule is **deprecated** in favour of `squid:MethodCyclomaticComplexity`.
-
------
-
-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. Modified complexity treats switch statements as a single decision point.
diff --git a/docs/rules/MoreThanOneLogger.md b/docs/rules/MoreThanOneLogger.md
deleted file mode 100644
index 432ee494..00000000
--- a/docs/rules/MoreThanOneLogger.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# MoreThanOneLogger
-**Category:** `pmd`
-**Rule Key:** `pmd:MoreThanOneLogger`
-> :warning: This rule is **deprecated** in favour of [S1312](https://rules.sonarsource.com/java/RSPEC-1312).
-
------
-
-Normally only one logger is used in each class.
diff --git a/docs/rules/NPathComplexity.md b/docs/rules/NPathComplexity.md
deleted file mode 100644
index cfa10c1f..00000000
--- a/docs/rules/NPathComplexity.md
+++ /dev/null
@@ -1,15 +0,0 @@
-# NPathComplexity
-**Category:** `pmd`
-**Rule Key:** `pmd:NPathComplexity`
-
-
------
-
-The NPath complexity of a method is the number of acyclic execution paths through that method. A threshold of 200 is generally considered the point where measures should be taken to reduce complexity. Example :
-
-public class Foo {
- void bar() {
- // lots of complicated code
- }
- }
-
diff --git a/docs/rules/NcssConstructorCount.md b/docs/rules/NcssConstructorCount.md
deleted file mode 100644
index f91b8ae9..00000000
--- a/docs/rules/NcssConstructorCount.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# NcssConstructorCount
-**Category:** `pmd`
-**Rule Key:** `pmd:NcssConstructorCount`
-> :warning: This rule is **deprecated** in favour of [S138](https://rules.sonarsource.com/java/RSPEC-138).
-
------
-
-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.
diff --git a/docs/rules/NcssMethodCount.md b/docs/rules/NcssMethodCount.md
deleted file mode 100644
index 5ce6f2e5..00000000
--- a/docs/rules/NcssMethodCount.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# NcssMethodCount
-**Category:** `pmd`
-**Rule Key:** `pmd:NcssMethodCount`
-> :warning: This rule is **deprecated** in favour of [S138](https://rules.sonarsource.com/java/RSPEC-138).
-
------
-
-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.
diff --git a/docs/rules/NcssTypeCount.md b/docs/rules/NcssTypeCount.md
deleted file mode 100644
index 260ec358..00000000
--- a/docs/rules/NcssTypeCount.md
+++ /dev/null
@@ -1,12 +0,0 @@
-# NcssTypeCount
-**Category:** `pmd`
-**Rule Key:** `pmd:NcssTypeCount`
-
-
------
-
-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.
-
-
-**Rule Key:** `pmd:NoPackage`
-> :warning: This rule is **deprecated** in favour of [S1220](https://rules.sonarsource.com/java/RSPEC-1220).
-
------
-
-Detects when a class or interface does not have a package definition. Example :
-
-// no package declaration
-public class ClassInDefaultPackage {
-}
-
diff --git a/docs/rules/NonCaseLabelInSwitchStatement.md b/docs/rules/NonCaseLabelInSwitchStatement.md
deleted file mode 100644
index ac2138a3..00000000
--- a/docs/rules/NonCaseLabelInSwitchStatement.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# NonCaseLabelInSwitchStatement
-**Category:** `pmd`
-**Rule Key:** `pmd:NonCaseLabelInSwitchStatement`
-> :warning: This rule is **deprecated** in favour of [S1219](https://rules.sonarsource.com/java/RSPEC-1219).
-
------
-
-A non-case label (e.g. a named break/continue label) was present in a switch statement. This legal, but confusing. It is easy to mix up the case labels and the non-case labels.
diff --git a/docs/rules/NonStaticInitializer.md b/docs/rules/NonStaticInitializer.md
deleted file mode 100644
index b1695382..00000000
--- a/docs/rules/NonStaticInitializer.md
+++ /dev/null
@@ -1,10 +0,0 @@
-# NonStaticInitializer
-**Category:** `pmd`
-**Rule Key:** `pmd:NonStaticInitializer`
-> :warning: This rule is **deprecated** in favour of [S1171](https://rules.sonarsource.com/java/RSPEC-1171).
-
------
-
-A nonstatic initializer block will be called any time a constructor is invoked (just prior to invoking the constructor). While this is a valid language construct, it is rarely used and is confusing. Example :
-public class MyClass {
diff --git a/docs/rules/NonThreadSafeSingleton.md b/docs/rules/NonThreadSafeSingleton.md
deleted file mode 100644
index 39c60312..00000000
--- a/docs/rules/NonThreadSafeSingleton.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# NonThreadSafeSingleton
-**Category:** `pmd`
// this block gets run before any call to a constructor {
System.out.println("I
- am about to construct myself");
}
}
-**Rule Key:** `pmd:NonThreadSafeSingleton`
-> :warning: This rule is **deprecated** in favour of [S2444](https://rules.sonarsource.com/java/RSPEC-2444).
-
------
-
-Non-thread safe singletons can result in bad state changes. Eliminate static singletons if possible by instantiating the object directly. Static singletons are usually not needed as only a single instance exists anyway. Other possible fixes are to synchronize the entire method or to use an initialize-on-demand holder class (do not use the double-check idiom). See Effective Java, item 48.
diff --git a/docs/rules/NullAssignment.md b/docs/rules/NullAssignment.md
deleted file mode 100644
index 486525b8..00000000
--- a/docs/rules/NullAssignment.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# NullAssignment
-**Category:** `pmd`
-**Rule Key:** `pmd:NullAssignment`
-
-
------
-
-Assigning a null to a variable (outside of its declaration) is usually bad form. Some times, the assignment is an indication that the programmer doesn't completely understand what is going on in the code. NOTE: This sort of assignment may in rare cases be useful to encourage garbage collection. If that's what you're using it for, by all means, disregard this rule :-)
diff --git a/docs/rules/OneDeclarationPerLine.md b/docs/rules/OneDeclarationPerLine.md
deleted file mode 100644
index deffa693..00000000
--- a/docs/rules/OneDeclarationPerLine.md
+++ /dev/null
@@ -1,15 +0,0 @@
-# OneDeclarationPerLine
-**Category:** `pmd`
-**Rule Key:** `pmd:OneDeclarationPerLine`
-> :warning: This rule is **deprecated** in favour of [S00122](https://rules.sonarsource.com/java/RSPEC-122).
-
------
-
-Java allows the use of several variables declaration of the same type on one line. However, it
-can lead to quite messy code. This rule looks for several declarations on the same line. Example:
-
-String name; // separate declarations
-String lastname;
-
-String name, lastname; // combined declaration, a violation
-
diff --git a/docs/rules/OnlyOneReturn.md b/docs/rules/OnlyOneReturn.md
deleted file mode 100644
index a8765ee2..00000000
--- a/docs/rules/OnlyOneReturn.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# OnlyOneReturn
-**Category:** `pmd`
-**Rule Key:** `pmd:OnlyOneReturn`
-> :warning: This rule is **deprecated** in favour of [S1142](https://rules.sonarsource.com/java/RSPEC-1142).
-
------
-
-A method should have only one exit point, and that should be the last statement in the method.
diff --git a/docs/rules/OptimizableToArrayCall.md b/docs/rules/OptimizableToArrayCall.md
deleted file mode 100644
index d7ca172a..00000000
--- a/docs/rules/OptimizableToArrayCall.md
+++ /dev/null
@@ -1,41 +0,0 @@
-# OptimizableToArrayCall
-**Category:** `pmd`
-**Rule Key:** `pmd:OptimizableToArrayCall`
-
-
------
-
-
-toArray(E[])
method should specify a target array of zero size. This allows the
- JVM to
- optimize the memory allocation and copying as much as possible.
-toArray()
method without an array
- is faster, but
- returns only an array of type Object[]
.
-Noncompliant Code Example
-
-List<Foo> foos = getFoos();
-
-// inefficient, the array needs to be zeroed out by the jvm before it is handed over to the toArray method
-Foo[] fooArray = foos.toArray(new Foo[foos.size()]);
-
-Compliant Solution
-
-List<Foo> foos = getFoos();
-
-// much better; this one allows the jvm to allocate an array of the correct size and effectively skip
-// the zeroing, since each array element will be overridden anyways
-Foo[] fooArray = foos.toArray(new Foo[0]);
-
diff --git a/docs/rules/OverrideBothEqualsAndHashcode.md b/docs/rules/OverrideBothEqualsAndHashcode.md
deleted file mode 100644
index 6d807f12..00000000
--- a/docs/rules/OverrideBothEqualsAndHashcode.md
+++ /dev/null
@@ -1,33 +0,0 @@
-# OverrideBothEqualsAndHashcode
-**Category:** `pmd`
-**Rule Key:** `pmd:OverrideBothEqualsAndHashcode`
-> :warning: This rule is **deprecated** in favour of [S1206](https://rules.sonarsource.com/java/RSPEC-1206).
-
------
-
-Override both public boolean Object.equals(Object other), and public int Object.hashCode(), or override neither. Even if you are inheriting a hashCode() from a parent class, consider implementing hashCode and explicitly delegating to your superclass. Example :
-
-// this is bad
-public class Bar {
- public boolean equals(Object o) {
- // do some comparison
- }
-}
-
-// and so is this
-public class Baz {
- public int hashCode() {
- // return some hash value
- }
-}
-
-// this is OK
-public class Foo {
- public boolean equals(Object other) {
- // do some comparison
- }
- public int hashCode() {
- // return some hash value
- }
-}
-
diff --git a/docs/rules/PackageCase.md b/docs/rules/PackageCase.md
deleted file mode 100644
index 762030ca..00000000
--- a/docs/rules/PackageCase.md
+++ /dev/null
@@ -1,13 +0,0 @@
-# PackageCase
-**Category:** `pmd`
-**Rule Key:** `pmd:PackageCase`
-> :warning: This rule is **deprecated** in favour of [S00120](https://rules.sonarsource.com/java/RSPEC-120).
-
------
-
-Detects when a package definition contains upper case characters. Example :
-
-package com.MyCompany; // <- should be lower case name
-public class SomeClass {
-}
-
diff --git a/docs/rules/PositionLiteralsFirstInCaseInsensitiveComparisons.md b/docs/rules/PositionLiteralsFirstInCaseInsensitiveComparisons.md
deleted file mode 100644
index f0662ba8..00000000
--- a/docs/rules/PositionLiteralsFirstInCaseInsensitiveComparisons.md
+++ /dev/null
@@ -1,16 +0,0 @@
-# PositionLiteralsFirstInCaseInsensitiveComparisons
-**Category:** `pmd`
-**Rule Key:** `pmd:PositionLiteralsFirstInCaseInsensitiveComparisons`
-> :warning: This rule is **deprecated** in favour of [S1132](https://rules.sonarsource.com/java/RSPEC-1132).
-
------
-
-Position literals first in comparisons, if the second argument is null then NullPointerExceptions
-can be avoided, they will just return false. Example:
-
-class Foo {
- boolean bar(String x) {
- return x.equalsIgnoreCase("2"); // should be "2".equalsIgnoreCase(x)
- }
-}
-
diff --git a/docs/rules/PositionLiteralsFirstInComparisons.md b/docs/rules/PositionLiteralsFirstInComparisons.md
deleted file mode 100644
index c1e6310e..00000000
--- a/docs/rules/PositionLiteralsFirstInComparisons.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# PositionLiteralsFirstInComparisons
-**Category:** `pmd`
-**Rule Key:** `pmd:PositionLiteralsFirstInComparisons`
-> :warning: This rule is **deprecated** in favour of [S1132](https://rules.sonarsource.com/java/RSPEC-1132).
-
------
-
-Position literals first in String comparisons - that way if the String is null you won't get a NullPointerException, it'll just return false.
diff --git a/docs/rules/PrematureDeclaration.md b/docs/rules/PrematureDeclaration.md
deleted file mode 100644
index d51d27c2..00000000
--- a/docs/rules/PrematureDeclaration.md
+++ /dev/null
@@ -1,22 +0,0 @@
-# PrematureDeclaration
-**Category:** `pmd`
-**Rule Key:** `pmd:PrematureDeclaration`
-> :warning: This rule is **deprecated** in favour of [S1941](https://rules.sonarsource.com/java/RSPEC-1941).
-
------
-
-Checks for variables that are defined before they might be used. A reference is deemed to be premature if it is created right before a block of code that doesn't use it that also has the ability to return or throw an exception. Example:
-
-public int getLength(String[] strings) {
-
- int length = 0; // declared prematurely
-
- if (strings == null || strings.length == 0) return 0;
-
- for (String str : strings) {
- length += str.length();
- }
-
- return length;
-}
-
diff --git a/docs/rules/PreserveStackTrace.md b/docs/rules/PreserveStackTrace.md
deleted file mode 100644
index 5124fd58..00000000
--- a/docs/rules/PreserveStackTrace.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# PreserveStackTrace
-**Category:** `pmd`
-**Rule Key:** `pmd:PreserveStackTrace`
-> :warning: This rule is **deprecated** in favour of [S1166](https://rules.sonarsource.com/java/RSPEC-1166).
-
------
-
-Throwing a new exception from a catch block without passing the original exception into the new Exception will cause the true stack trace to be lost, and can make it difficult to debug effectively.
diff --git a/docs/rules/ProperCloneImplementation.md b/docs/rules/ProperCloneImplementation.md
deleted file mode 100644
index 8ece5d5e..00000000
--- a/docs/rules/ProperCloneImplementation.md
+++ /dev/null
@@ -1,15 +0,0 @@
-# ProperCloneImplementation
-**Category:** `pmd`
-**Rule Key:** `pmd:ProperCloneImplementation`
-> :warning: This rule is **deprecated** in favour of [S1182](https://rules.sonarsource.com/java/RSPEC-1182).
-
------
-
-Object clone() should be implemented with super.clone(). Example :
-
-class Foo{
- public Object clone(){
- return new Foo(); // This is bad
- }
-}
-
diff --git a/docs/rules/ProperLogger.md b/docs/rules/ProperLogger.md
deleted file mode 100644
index 07b655e8..00000000
--- a/docs/rules/ProperLogger.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# ProperLogger
-**Category:** `pmd`
-**Rule Key:** `pmd:ProperLogger`
-> :warning: This rule is **deprecated** in favour of [S1312](https://rules.sonarsource.com/java/RSPEC-1312).
-
------
-
-Logger should normally be defined private static final and have the correct class. Private final Log log; is also allowed for rare cases when loggers need to be passed around, but the logger needs to be passed into the constructor.
diff --git a/docs/rules/RedundantFieldInitializer.md b/docs/rules/RedundantFieldInitializer.md
deleted file mode 100644
index d1fa57e9..00000000
--- a/docs/rules/RedundantFieldInitializer.md
+++ /dev/null
@@ -1,30 +0,0 @@
-# RedundantFieldInitializer
-**Category:** `pmd`
-**Rule Key:** `pmd:RedundantFieldInitializer`
-
-
------
-
-Java will initialize fields with known default values so any explicit initialization of those same defaults
-is redundant and results in a larger class file (approximately three additional bytecode instructions per field). Example:
-
-public class C {
- boolean b = false; // examples of redundant initializers
- byte by = 0;
- short s = 0;
- char c = 0;
- int i = 0;
- long l = 0;
-
- float f = .0f; // all possible float literals
- doable d = 0d; // all possible double literals
- Object o = null;
-
- MyClass mca[] = null;
- int i1 = 0, ia1[] = null;
-
- class Nested {
- boolean b = false;
- }
-}
-
diff --git a/docs/rules/RemoteInterfaceNamingConvention.md b/docs/rules/RemoteInterfaceNamingConvention.md
deleted file mode 100644
index 4d69ea0f..00000000
--- a/docs/rules/RemoteInterfaceNamingConvention.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# RemoteInterfaceNamingConvention
-**Category:** `pmd`
-**Rule Key:** `pmd:RemoteInterfaceNamingConvention`
-
-
------
-
-Remote Interface of a Session EJB should NOT be suffixed.
diff --git a/docs/rules/RemoteSessionInterfaceNamingConvention.md b/docs/rules/RemoteSessionInterfaceNamingConvention.md
deleted file mode 100644
index 1a0ffc4c..00000000
--- a/docs/rules/RemoteSessionInterfaceNamingConvention.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# RemoteSessionInterfaceNamingConvention
-**Category:** `pmd`
-**Rule Key:** `pmd:RemoteSessionInterfaceNamingConvention`
-
-
------
-
-Remote Home interface of a Session EJB should be suffixed by "Home".
diff --git a/docs/rules/ReplaceEnumerationWithIterator.md b/docs/rules/ReplaceEnumerationWithIterator.md
deleted file mode 100644
index 23dfc8dd..00000000
--- a/docs/rules/ReplaceEnumerationWithIterator.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# ReplaceEnumerationWithIterator
-**Category:** `pmd`
-**Rule Key:** `pmd:ReplaceEnumerationWithIterator`
-> :warning: This rule is **deprecated** in favour of [S1150](https://rules.sonarsource.com/java/RSPEC-1150).
-
------
-
-Consider replacing this Enumeration with the newer java.util.Iterator
diff --git a/docs/rules/ReplaceHashtableWithMap.md b/docs/rules/ReplaceHashtableWithMap.md
deleted file mode 100644
index 37471019..00000000
--- a/docs/rules/ReplaceHashtableWithMap.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# ReplaceHashtableWithMap
-**Category:** `pmd`
-**Rule Key:** `pmd:ReplaceHashtableWithMap`
-> :warning: This rule is **deprecated** in favour of [S1149](https://rules.sonarsource.com/java/RSPEC-1149).
-
------
-
-Consider replacing this Hashtable with the newer java.util.Map
diff --git a/docs/rules/ReplaceVectorWithList.md b/docs/rules/ReplaceVectorWithList.md
deleted file mode 100644
index de41fa97..00000000
--- a/docs/rules/ReplaceVectorWithList.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# ReplaceVectorWithList
-**Category:** `pmd`
-**Rule Key:** `pmd:ReplaceVectorWithList`
-> :warning: This rule is **deprecated** in favour of [S1149](https://rules.sonarsource.com/java/RSPEC-1149).
-
------
-
-Consider replacing Vector usages with the newer java.util.ArrayList if expensive threadsafe operation is not required.
diff --git a/docs/rules/ReturnEmptyArrayRatherThanNull.md b/docs/rules/ReturnEmptyArrayRatherThanNull.md
deleted file mode 100644
index 5874df46..00000000
--- a/docs/rules/ReturnEmptyArrayRatherThanNull.md
+++ /dev/null
@@ -1,26 +0,0 @@
-# ReturnEmptyArrayRatherThanNull
-**Category:** `pmd`
-**Rule Key:** `pmd:ReturnEmptyArrayRatherThanNull`
-> :warning: This rule is **deprecated** in favour of [S1168](https://rules.sonarsource.com/java/RSPEC-1168).
-
------
-
-For any method that returns an array, it's a better behavior to return an empty array rather than a null reference. Example :
-
-public class Example
-{
- // Not a good idea...
- public int []badBehavior()
- {
- // ...
- return null;
- }
-
- // Good behavior
- public String[] bonnePratique()
- {
- //...
- return new String[0];
- }
-}
-
diff --git a/docs/rules/ReturnFromFinallyBlock.md b/docs/rules/ReturnFromFinallyBlock.md
deleted file mode 100644
index 43c828d3..00000000
--- a/docs/rules/ReturnFromFinallyBlock.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# ReturnFromFinallyBlock
-**Category:** `pmd`
-**Rule Key:** `pmd:ReturnFromFinallyBlock`
-> :warning: This rule is **deprecated** in favour of [S1143](https://rules.sonarsource.com/java/RSPEC-1143).
-
------
-
-Avoid returning from a finally block - this can discard exceptions.
diff --git a/docs/rules/ShortClassName.md b/docs/rules/ShortClassName.md
deleted file mode 100644
index 5be899e0..00000000
--- a/docs/rules/ShortClassName.md
+++ /dev/null
@@ -1,12 +0,0 @@
-# ShortClassName
-**Category:** `pmd`
-**Rule Key:** `pmd:ShortClassName`
-> :warning: This rule is **deprecated** in favour of [S00101](https://rules.sonarsource.com/java/RSPEC-101).
-
------
-
-Classnames with fewer than five characters are not recommended. Example:
-
-public class Foo {
-}
-
diff --git a/docs/rules/ShortInstantiation.md b/docs/rules/ShortInstantiation.md
deleted file mode 100644
index 5f16c723..00000000
--- a/docs/rules/ShortInstantiation.md
+++ /dev/null
@@ -1,14 +0,0 @@
-# ShortInstantiation
-**Category:** `pmd`
-**Rule Key:** `pmd:ShortInstantiation`
-
-
------
-
-In JDK 1.5, calling new Short() causes memory allocation. Short.valueOf() is more memory friendly. Example :
-
-public class Foo {
-private Short i = new Short(0); // change to Short i =
-Short.valueOf(0);
-}
-
diff --git a/docs/rules/ShortMethodName.md b/docs/rules/ShortMethodName.md
deleted file mode 100644
index b9e924a4..00000000
--- a/docs/rules/ShortMethodName.md
+++ /dev/null
@@ -1,14 +0,0 @@
-# ShortMethodName
-**Category:** `pmd`
-**Rule Key:** `pmd:ShortMethodName`
-> :warning: This rule is **deprecated** in favour of [S00100](https://rules.sonarsource.com/java/RSPEC-100).
-
------
-
-Detects when very short method names are used. Example :
-
-public class ShortMethod {
- public void a( int i ) { // Violation
- }
-}
-
diff --git a/docs/rules/ShortVariable.md b/docs/rules/ShortVariable.md
deleted file mode 100644
index 736ddc9c..00000000
--- a/docs/rules/ShortVariable.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# ShortVariable
-**Category:** `pmd`
-**Rule Key:** `pmd:ShortVariable`
-> :warning: This rule is **deprecated** in favour of [S00117](https://rules.sonarsource.com/java/RSPEC-117).
-
------
-
-Detects when a field, local, or parameter has a very short name.
diff --git a/docs/rules/SignatureDeclareThrowsException.md b/docs/rules/SignatureDeclareThrowsException.md
deleted file mode 100644
index 82b7beba..00000000
--- a/docs/rules/SignatureDeclareThrowsException.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# SignatureDeclareThrowsException
-**Category:** `pmd`
-**Rule Key:** `pmd:SignatureDeclareThrowsException`
-> :warning: This rule is **deprecated** in favour of [S00112](https://rules.sonarsource.com/java/RSPEC-112).
-
------
-
-It is unclear which exceptions that can be thrown from the methods. It might be difficult to document and understand the vague interfaces. Use either a class derived from RuntimeException or a checked exception.
diff --git a/docs/rules/SignatureDeclareThrowsExceptionWithTypeResolution.md b/docs/rules/SignatureDeclareThrowsExceptionWithTypeResolution.md
deleted file mode 100644
index fb4785c4..00000000
--- a/docs/rules/SignatureDeclareThrowsExceptionWithTypeResolution.md
+++ /dev/null
@@ -1,16 +0,0 @@
-# SignatureDeclareThrowsExceptionWithTypeResolution
-**Category:** `pmd`
-**Rule Key:** `pmd:SignatureDeclareThrowsExceptionWithTypeResolution`
-> :warning: This rule is **deprecated** in favour of [S00112](https://rules.sonarsource.com/java/RSPEC-112).
-
------
-
-It is unclear which exceptions that can be thrown from the methods.
-It might be difficult to document and understand the vague interfaces.
-Use either a class derived from RuntimeException or a checked exception.
-
-JUnit classes are excluded. Example:
-
-public void methodThrowingException() throws Exception {
-}
-
diff --git a/docs/rules/SimpleDateFormatNeedsLocale.md b/docs/rules/SimpleDateFormatNeedsLocale.md
deleted file mode 100644
index ab01298e..00000000
--- a/docs/rules/SimpleDateFormatNeedsLocale.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# SimpleDateFormatNeedsLocale
-**Category:** `pmd`
-**Rule Key:** `pmd:SimpleDateFormatNeedsLocale`
-
-
------
-
-Be sure to specify a Locale when creating a new instance of SimpleDateFormat.
diff --git a/docs/rules/SimplifiedTernary.md b/docs/rules/SimplifiedTernary.md
deleted file mode 100644
index 56778ff2..00000000
--- a/docs/rules/SimplifiedTernary.md
+++ /dev/null
@@ -1,31 +0,0 @@
-# SimplifiedTernary
-**Category:** `pmd`
-**Rule Key:** `pmd:SimplifiedTernary`
-
-
------
-
-
-public class Foo {
- public boolean test() {
- return condition ? true : something(); // can be as simple as return condition || something();
- }
-
- public void test2() {
- final boolean value = condition ? false : something(); // can be as simple as value = !condition && something();
- }
-
- public boolean test3() {
- return condition ? something() : true; // can be as simple as return !condition || something();
- }
-
- public void test4() {
- final boolean otherValue = condition ? something() : false; // can be as simple as condition && something();
- }
-}
-
diff --git a/docs/rules/SimplifyBooleanAssertion.md b/docs/rules/SimplifyBooleanAssertion.md
deleted file mode 100644
index aabafc77..00000000
--- a/docs/rules/SimplifyBooleanAssertion.md
+++ /dev/null
@@ -1,16 +0,0 @@
-# SimplifyBooleanAssertion
-**Category:** `pmd-unit-tests`
-**Rule Key:** `pmd-unit-tests:SimplifyBooleanAssertion`
-
-
------
-
-Avoid negation in an assertTrue or assertFalse test. For example, rephrase: assertTrue(!expr); as: assertFalse(expr);
-
-public class SimpleTest extends TestCase {
- public void testX() {
- assertTrue("not empty", !r.isEmpty()); // violation, replace with assertFalse("not empty", r.isEmpty())
- assertFalse(!r.isEmpty()); // violation, replace with assertTrue("empty", r.isEmpty())
- }
-}
-
diff --git a/docs/rules/SimplifyBooleanExpressions.md b/docs/rules/SimplifyBooleanExpressions.md
deleted file mode 100644
index 4ab8c84b..00000000
--- a/docs/rules/SimplifyBooleanExpressions.md
+++ /dev/null
@@ -1,17 +0,0 @@
-# SimplifyBooleanExpressions
-**Category:** `pmd`
-**Rule Key:** `pmd:SimplifyBooleanExpressions`
-> :warning: This rule is **deprecated** in favour of [S1125](https://rules.sonarsource.com/java/RSPEC-1125).
-
------
-
-Avoid unnecessary comparisons in boolean expressions - this complicates simple code. Example :
-
-public class Bar {
- // can be simplified to
- // bar = isFoo();
- private boolean bar = (isFoo() == true);
-
- public isFoo() { return false;}
-}
-
diff --git a/docs/rules/SimplifyBooleanReturns.md b/docs/rules/SimplifyBooleanReturns.md
deleted file mode 100644
index 87c3df5f..00000000
--- a/docs/rules/SimplifyBooleanReturns.md
+++ /dev/null
@@ -1,23 +0,0 @@
-# SimplifyBooleanReturns
-**Category:** `pmd`
-**Rule Key:** `pmd:SimplifyBooleanReturns`
-> :warning: This rule is **deprecated** in favour of [S1126](https://rules.sonarsource.com/java/RSPEC-1126).
-
------
-
-Avoid unnecessary if..then..else statements when returning a boolean. Example :
-
-public class Foo {
- private int bar =2;
- public boolean isBarEqualsTo(int x) {
- // this bit of code
- if (bar == x) {
- return true;
- } else {
- return false;
- }
- // can be replaced with a simple
- // return bar == x;
- }
-}
-
diff --git a/docs/rules/SimplifyConditional.md b/docs/rules/SimplifyConditional.md
deleted file mode 100644
index 6d5af3d1..00000000
--- a/docs/rules/SimplifyConditional.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# SimplifyConditional
-**Category:** `pmd`
-**Rule Key:** `pmd:SimplifyConditional`
-
-
------
-
-No need to check for null before an instanceof; the instanceof keyword returns false when given a null argument.
diff --git a/docs/rules/SimplifyStartsWith.md b/docs/rules/SimplifyStartsWith.md
deleted file mode 100644
index 810ba790..00000000
--- a/docs/rules/SimplifyStartsWith.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# SimplifyStartsWith
-**Category:** `pmd`
-**Rule Key:** `pmd:SimplifyStartsWith`
-
-
------
-
-Since it passes in a literal of length 1, this call to String.startsWith can be rewritten using String.charAt(0) to save some time.
diff --git a/docs/rules/SingleMethodSingleton.md b/docs/rules/SingleMethodSingleton.md
deleted file mode 100644
index b3608e2f..00000000
--- a/docs/rules/SingleMethodSingleton.md
+++ /dev/null
@@ -1,30 +0,0 @@
-# SingleMethodSingleton
-**Category:** `pmd`
-**Rule Key:** `pmd:SingleMethodSingleton`
-
-
------
-
-
-public class Singleton {
- private static Singleton singleton = new Singleton( );
-
- private Singleton() { }
-
- public static Singleton getInstance( ) {
- return singleton;
- }
-
- public static Singleton getInstance(Object obj) {
- Singleton singleton = (Singleton) obj;
- return singleton; //violation
- }
-}
-
diff --git a/docs/rules/SingletonClassReturningNewInstance.md b/docs/rules/SingletonClassReturningNewInstance.md
deleted file mode 100644
index d020e22b..00000000
--- a/docs/rules/SingletonClassReturningNewInstance.md
+++ /dev/null
@@ -1,25 +0,0 @@
-# SingletonClassReturningNewInstance
-**Category:** `pmd`
-**Rule Key:** `pmd:SingletonClassReturningNewInstance`
-
-
------
-
-
-class Singleton {
- private static Singleton instance = null;
-
- public static Singleton getInstance() {
- synchronized(Singleton.class) {
- return new Singleton();
- }
- }
-}
-
diff --git a/docs/rules/SingularField.md b/docs/rules/SingularField.md
deleted file mode 100644
index 230367db..00000000
--- a/docs/rules/SingularField.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# SingularField
-**Category:** `pmd`
-**Rule Key:** `pmd:SingularField`
-
-
------
-
-A field that's only used by one method could perhaps be replaced by a local variable.
diff --git a/docs/rules/StaticEJBFieldShouldBeFinal.md b/docs/rules/StaticEJBFieldShouldBeFinal.md
deleted file mode 100644
index 2f17acbc..00000000
--- a/docs/rules/StaticEJBFieldShouldBeFinal.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# StaticEJBFieldShouldBeFinal
-**Category:** `pmd`
-**Rule Key:** `pmd:StaticEJBFieldShouldBeFinal`
-
-
------
-
-According to the J2EE specification (p.494), an EJB should not have any static fields with write access. However, static read only fields are allowed. This ensures proper behavior especially when instances are distributed by the container on several JREs.
diff --git a/docs/rules/StdCyclomaticComplexity.md b/docs/rules/StdCyclomaticComplexity.md
deleted file mode 100644
index 3f1379f8..00000000
--- a/docs/rules/StdCyclomaticComplexity.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# StdCyclomaticComplexity
-**Category:** `pmd`
-**Rule Key:** `pmd:StdCyclomaticComplexity`
-> :warning: This rule is **deprecated** in favour of `squid:MethodCyclomaticComplexity`, `squid:ClassCyclomaticComplexity`.
-
------
-
-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.
diff --git a/docs/rules/StringBufferInstantiationWithChar.md b/docs/rules/StringBufferInstantiationWithChar.md
deleted file mode 100644
index adc4bce1..00000000
--- a/docs/rules/StringBufferInstantiationWithChar.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# StringBufferInstantiationWithChar
-**Category:** `pmd`
-**Rule Key:** `pmd:StringBufferInstantiationWithChar`
-> :warning: This rule is **deprecated** in favour of [S1317](https://rules.sonarsource.com/java/RSPEC-1317).
-
------
-
-StringBuffer sb = new StringBuffer('c'); The char will be converted into int to intialize StringBuffer size.
diff --git a/docs/rules/StringInstantiation.md b/docs/rules/StringInstantiation.md
deleted file mode 100644
index d19eaedf..00000000
--- a/docs/rules/StringInstantiation.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# StringInstantiation
-**Category:** `pmd`
-**Rule Key:** `pmd:StringInstantiation`
-
-
------
-
-Avoid instantiating String objects; this is usually unnecessary.
diff --git a/docs/rules/StringToString.md b/docs/rules/StringToString.md
deleted file mode 100644
index d47a2ec8..00000000
--- a/docs/rules/StringToString.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# StringToString
-**Category:** `pmd`
-**Rule Key:** `pmd:StringToString`
-> :warning: This rule is **deprecated** in favour of [S1858](https://rules.sonarsource.com/java/RSPEC-1858).
-
------
-
-Avoid calling toString() on String objects; this is unnecessary.
diff --git a/docs/rules/SuspiciousConstantFieldName.md b/docs/rules/SuspiciousConstantFieldName.md
deleted file mode 100644
index 15818027..00000000
--- a/docs/rules/SuspiciousConstantFieldName.md
+++ /dev/null
@@ -1,16 +0,0 @@
-# SuspiciousConstantFieldName
-**Category:** `pmd`
-**Rule Key:** `pmd:SuspiciousConstantFieldName`
-> :warning: This rule is **deprecated** in favour of [S00116](https://rules.sonarsource.com/java/RSPEC-116).
-
------
-
-A field name is all in uppercase characters, which in Sun's Java naming conventions indicate a constant. However, the field is not final. Example :
-
-public class Foo {
- // this is bad, since someone could accidentally
- // do PI = 2.71828; which is actualy e
- // final double PI = 3.16; is ok
- double PI = 3.16;
-}
-
diff --git a/docs/rules/SuspiciousEqualsMethodName.md b/docs/rules/SuspiciousEqualsMethodName.md
deleted file mode 100644
index 7a6eb44a..00000000
--- a/docs/rules/SuspiciousEqualsMethodName.md
+++ /dev/null
@@ -1,18 +0,0 @@
-# SuspiciousEqualsMethodName
-**Category:** `pmd`
-**Rule Key:** `pmd:SuspiciousEqualsMethodName`
-> :warning: This rule is **deprecated** in favour of [S1201](https://rules.sonarsource.com/java/RSPEC-1201).
-
------
-
-The method name and parameter number are suspiciously close to equals(Object), which may mean you are intending to override the equals(Object) method. Example :
-
-public class Foo {
- public int equals(Object o) {
- // oops, this probably was supposed to be boolean equals
- }
- public boolean equals(String s) {
- // oops, this probably was supposed to be equals(Object)
- }
-}
-
diff --git a/docs/rules/SuspiciousHashcodeMethodName.md b/docs/rules/SuspiciousHashcodeMethodName.md
deleted file mode 100644
index 362a51d3..00000000
--- a/docs/rules/SuspiciousHashcodeMethodName.md
+++ /dev/null
@@ -1,14 +0,0 @@
-# SuspiciousHashcodeMethodName
-**Category:** `pmd`
-**Rule Key:** `pmd:SuspiciousHashcodeMethodName`
-> :warning: This rule is **deprecated** in favour of [S1221](https://rules.sonarsource.com/java/RSPEC-1221).
-
------
-
-The method name and return type are suspiciously close to hashCode(), which may mean you are intending to override the hashCode() method. Example :
-
-public class Foo {
- public int hashcode() {
- // oops, this probably was supposed to be hashCode
- }
-}
diff --git a/docs/rules/SuspiciousOctalEscape.md b/docs/rules/SuspiciousOctalEscape.md
deleted file mode 100644
index c0534466..00000000
--- a/docs/rules/SuspiciousOctalEscape.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# SuspiciousOctalEscape
-**Category:** `pmd`
-**Rule Key:** `pmd:SuspiciousOctalEscape`
-
-
------
-
-A suspicious octal escape sequence was found inside a String literal. The Java language specification (section 3.10.6) says an octal escape sequence inside a literal String shall consist of a backslash followed by: OctalDigit | OctalDigit OctalDigit | ZeroToThree OctalDigit OctalDigit Any octal escape sequence followed by non-octal digits can be confusing, e.g. "\038" is interpreted as the octal escape sequence "\03" followed by the literal character 8.
diff --git a/docs/rules/SwitchDensity.md b/docs/rules/SwitchDensity.md
deleted file mode 100644
index c04ef3c5..00000000
--- a/docs/rules/SwitchDensity.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# SwitchDensity
-**Category:** `pmd`
-**Rule Key:** `pmd:SwitchDensity`
-> :warning: This rule is **deprecated** in favour of [S1151](https://rules.sonarsource.com/java/RSPEC-1151).
-
------
-
-A high ratio of statements to labels in a switch statement implies that the switch statement is doing too much work. Consider moving the statements into new methods, or creating subclasses based on the switch variable.
diff --git a/docs/rules/SwitchStmtsShouldHaveDefault.md b/docs/rules/SwitchStmtsShouldHaveDefault.md
deleted file mode 100644
index 48dab687..00000000
--- a/docs/rules/SwitchStmtsShouldHaveDefault.md
+++ /dev/null
@@ -1,18 +0,0 @@
-# SwitchStmtsShouldHaveDefault
-**Category:** `pmd`
-**Rule Key:** `pmd:SwitchStmtsShouldHaveDefault`
-> :warning: This rule is **deprecated** in favour of `squid:SwitchLastCaseIsDefaultCheck`.
-
------
-
-Switch statements should have a default label. Example :
-
-public class Foo {
- public void bar() {
- int x = 2;
- switch (x) {
- case 2: int j = 8;
- }
- }
-}
-
diff --git a/docs/rules/SystemPrintln.md b/docs/rules/SystemPrintln.md
deleted file mode 100644
index 46395f9a..00000000
--- a/docs/rules/SystemPrintln.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# SystemPrintln
-**Category:** `pmd`
-**Rule Key:** `pmd:SystemPrintln`
-> :warning: This rule is **deprecated** in favour of [S106](https://rules.sonarsource.com/java/RSPEC-106).
-
------
-
-System.(out|err).print is used, consider using a logger.
diff --git a/docs/rules/TestClassWithoutTestCases.md b/docs/rules/TestClassWithoutTestCases.md
deleted file mode 100644
index 5bdf97d4..00000000
--- a/docs/rules/TestClassWithoutTestCases.md
+++ /dev/null
@@ -1,17 +0,0 @@
-# TestClassWithoutTestCases
-**Category:** `pmd-unit-tests`
-**Rule Key:** `pmd-unit-tests:TestClassWithoutTestCases`
-
-
------
-
-Test classes end with the suffix Test. Having a non-test class with that name is not a good practice, since most people will assume it is a test case. Test classes have test methods named testXXX.
-Beware: This rule doesn't support JUnit 4.x's @Test annotation.
-
-public class CarTest { // violation, consider changing the name of the class if it is not a test
- // consider adding test methods if it is a test
- public static void main(String[] args) {
- // do something
- }
-}
-
diff --git a/docs/rules/TooFewBranchesForASwitchStatement.md b/docs/rules/TooFewBranchesForASwitchStatement.md
deleted file mode 100644
index 273a5d39..00000000
--- a/docs/rules/TooFewBranchesForASwitchStatement.md
+++ /dev/null
@@ -1,23 +0,0 @@
-# TooFewBranchesForASwitchStatement
-**Category:** `pmd`
-**Rule Key:** `pmd:TooFewBranchesForASwitchStatement`
-> :warning: This rule is **deprecated** in favour of [S1301](https://rules.sonarsource.com/java/RSPEC-1301).
-
------
-
-Swith are designed complex branches, and allow branches to share treatement. Using a switch for only a few branches is ill advised, as switches are not as easy to understand as if. In this case, it's most likely is a good idea to use a if statement instead, at least to increase code readability. Example :
-
-// With a minimumNumberCaseForASwitch of 3
-public class Foo {
- public void bar() {
- switch (condition) {
- case ONE:
- instruction;
- break;
- default:
- break; // not enough for a 'switch' stmt,
- // a simple 'if' stmt would have been more appropriate
- }
- }
-}
-
diff --git a/docs/rules/TooManyFields.md b/docs/rules/TooManyFields.md
deleted file mode 100644
index aadf3598..00000000
--- a/docs/rules/TooManyFields.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# TooManyFields
-**Category:** `pmd`
-**Rule Key:** `pmd:TooManyFields`
-
-
------
-
-Classes that have too many fields could be redesigned to have fewer fields, possibly through some nested object grouping of some of the information. For example, a class with city/state/zip fields could instead have one Address field.
diff --git a/docs/rules/TooManyMethods.md b/docs/rules/TooManyMethods.md
deleted file mode 100644
index d204581d..00000000
--- a/docs/rules/TooManyMethods.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# TooManyMethods
-**Category:** `pmd`
-**Rule Key:** `pmd:TooManyMethods`
-> :warning: This rule is **deprecated** in favour of [S1448](https://rules.sonarsource.com/java/RSPEC-1448).
-
------
-
-A class with too many methods is probably a good suspect for refactoring, in order to reduce its complexity and find a way to have more fine grained objects.
diff --git a/docs/rules/TooManyStaticImports.md b/docs/rules/TooManyStaticImports.md
deleted file mode 100644
index 6d1faaaa..00000000
--- a/docs/rules/TooManyStaticImports.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# TooManyStaticImports
-**Category:** `pmd`
-**Rule Key:** `pmd:TooManyStaticImports`
-
-
------
-
-If you overuse the static import feature, it can make your program unreadable and unmaintainable, polluting its namespace with all the static members you import. Readers of your code (including you, a few months after you wrote it) will not know which class a static member comes from (Sun 1.5 Language Guide).
diff --git a/docs/rules/UncommentedEmptyConstructor.md b/docs/rules/UncommentedEmptyConstructor.md
deleted file mode 100644
index c9ecfd4c..00000000
--- a/docs/rules/UncommentedEmptyConstructor.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# UncommentedEmptyConstructor
-**Category:** `pmd`
-**Rule Key:** `pmd:UncommentedEmptyConstructor`
-> :warning: This rule is **deprecated** in favour of [S2094](https://rules.sonarsource.com/java/RSPEC-2094).
-
------
-
-Uncommented Empty Constructor finds instances where a constructor does not contain statements, but there is no comment. By explicitly commenting empty constructors it is easier to distinguish between intentional (commented) and unintentional empty constructors.
diff --git a/docs/rules/UncommentedEmptyMethodBody.md b/docs/rules/UncommentedEmptyMethodBody.md
deleted file mode 100644
index f5a63f91..00000000
--- a/docs/rules/UncommentedEmptyMethodBody.md
+++ /dev/null
@@ -1,10 +0,0 @@
-# UncommentedEmptyMethodBody
-**Category:** `pmd`
-**Rule Key:** `pmd:UncommentedEmptyMethodBody`
-> :warning: This rule is **deprecated** in favour of [S1186](https://rules.sonarsource.com/java/RSPEC-1186).
-
------
-
-
-**Rule Key:** `pmd:UnconditionalIfStatement`
-> :warning: This rule is **deprecated** in favour of [S2583](https://rules.sonarsource.com/java/RSPEC-2583).
-
------
-
-Do not use if statements that are always true or always false.
diff --git a/docs/rules/UnnecessaryBooleanAssertion.md b/docs/rules/UnnecessaryBooleanAssertion.md
deleted file mode 100644
index 0e5f69cf..00000000
--- a/docs/rules/UnnecessaryBooleanAssertion.md
+++ /dev/null
@@ -1,14 +0,0 @@
-# UnnecessaryBooleanAssertion
-**Category:** `pmd-unit-tests`
-**Rule Key:** `pmd-unit-tests:UnnecessaryBooleanAssertion`
-
-
------
-
-A JUnit test assertion with a boolean literal is unnecessary since it always will eval to the same thing. Consider using flow control (in case of assertTrue(false) or similar) or simply removing statements like assertTrue(true) and assertFalse(false). If you just want a test to halt, use the fail method.
-
-public class SimpleTest extends TestCase {
- public void testX() {
- assertTrue(true); // violation
- }
-}
diff --git a/docs/rules/UnnecessaryCaseChange.md b/docs/rules/UnnecessaryCaseChange.md
deleted file mode 100644
index 2a9d602f..00000000
--- a/docs/rules/UnnecessaryCaseChange.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# UnnecessaryCaseChange
-**Category:** `pmd`
-**Rule Key:** `pmd:UnnecessaryCaseChange`
-> :warning: This rule is **deprecated** in favour of [S1157](https://rules.sonarsource.com/java/RSPEC-1157).
-
------
-
-Using equalsIgnoreCase() is faster than using toUpperCase/toLowerCase().equals()
diff --git a/docs/rules/UnnecessaryConstructor.md b/docs/rules/UnnecessaryConstructor.md
deleted file mode 100644
index 1e666689..00000000
--- a/docs/rules/UnnecessaryConstructor.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# UnnecessaryConstructor
-**Category:** `pmd`
-**Rule Key:** `pmd:UnnecessaryConstructor`
-> :warning: This rule is **deprecated** in favour of [S1186](https://rules.sonarsource.com/java/RSPEC-1186).
-
------
-
-This rule detects when a constructor is not necessary; i.e., when there's only one constructor, it's public, has an empty body, and takes no arguments.
diff --git a/docs/rules/UnnecessaryConversionTemporary.md b/docs/rules/UnnecessaryConversionTemporary.md
deleted file mode 100644
index 7b5b87bf..00000000
--- a/docs/rules/UnnecessaryConversionTemporary.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# UnnecessaryConversionTemporary
-**Category:** `pmd`
-**Rule Key:** `pmd:UnnecessaryConversionTemporary`
-> :warning: This rule is **deprecated** in favour of [S1158](https://rules.sonarsource.com/java/RSPEC-1158).
-
------
-
-Avoid unnecessary temporaries when converting primitives to Strings
diff --git a/docs/rules/UnnecessaryFinalModifier.md b/docs/rules/UnnecessaryFinalModifier.md
deleted file mode 100644
index 4de8c53f..00000000
--- a/docs/rules/UnnecessaryFinalModifier.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# UnnecessaryFinalModifier
-**Category:** `pmd`
-**Rule Key:** `pmd:UnnecessaryFinalModifier`
-
-
------
-
-When a class has the final modifier, all the methods are automatically final.
diff --git a/docs/rules/UnnecessaryFullyQualifiedName.md b/docs/rules/UnnecessaryFullyQualifiedName.md
deleted file mode 100644
index d0bcabbf..00000000
--- a/docs/rules/UnnecessaryFullyQualifiedName.md
+++ /dev/null
@@ -1,17 +0,0 @@
-# UnnecessaryFullyQualifiedName
-**Category:** `pmd`
-**Rule Key:** `pmd:UnnecessaryFullyQualifiedName`
-
-
------
-
-Import statements allow the use of non-fully qualified names. The use of a fully qualified name
-which is covered by an import statement is redundant. Consider using the non-fully qualified name. Example:
-
-import java.util.List;
-
-public class Foo {
- private java.util.List list1; // Unnecessary FQN
- private List list2; // More appropriate given import of 'java.util.List'
-}
-
diff --git a/docs/rules/UnnecessaryLocalBeforeReturn.md b/docs/rules/UnnecessaryLocalBeforeReturn.md
deleted file mode 100644
index d130e7dd..00000000
--- a/docs/rules/UnnecessaryLocalBeforeReturn.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# UnnecessaryLocalBeforeReturn
-**Category:** `pmd`
-**Rule Key:** `pmd:UnnecessaryLocalBeforeReturn`
-> :warning: This rule is **deprecated** in favour of [S1488](https://rules.sonarsource.com/java/RSPEC-1488).
-
------
-
-Avoid unnecessarily creating local variables
diff --git a/docs/rules/UnnecessaryParentheses.md b/docs/rules/UnnecessaryParentheses.md
deleted file mode 100644
index 7aec3784..00000000
--- a/docs/rules/UnnecessaryParentheses.md
+++ /dev/null
@@ -1,15 +0,0 @@
-# UnnecessaryParentheses
-**Category:** `pmd`
-**Rule Key:** `pmd:UnnecessaryParentheses`
-> :warning: This rule is **deprecated** in favour of `squid:UselessParenthesesCheck`.
-
------
-
-Sometimes expressions are wrapped in unnecessary parentheses, making them look like a function call. Example :
-
-public class Foo {
- boolean bar() {
- return (true);
- }
-}
-
diff --git a/docs/rules/UnnecessaryReturn.md b/docs/rules/UnnecessaryReturn.md
deleted file mode 100644
index 6087ae87..00000000
--- a/docs/rules/UnnecessaryReturn.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# UnnecessaryReturn
-**Category:** `pmd`
-**Rule Key:** `pmd:UnnecessaryReturn`
-
-
------
-
-Avoid unnecessary return statements
diff --git a/docs/rules/UnnecessaryWrapperObjectCreation.md b/docs/rules/UnnecessaryWrapperObjectCreation.md
deleted file mode 100644
index da95fe64..00000000
--- a/docs/rules/UnnecessaryWrapperObjectCreation.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# UnnecessaryWrapperObjectCreation
-**Category:** `pmd`
-**Rule Key:** `pmd:UnnecessaryWrapperObjectCreation`
-> :warning: This rule is **deprecated** in favour of [S1158](https://rules.sonarsource.com/java/RSPEC-1158).
-
------
-
-Parsing method should be called directy instead.
diff --git a/docs/rules/UnsynchronizedStaticDateFormatter.md b/docs/rules/UnsynchronizedStaticDateFormatter.md
deleted file mode 100644
index 8ee84ff0..00000000
--- a/docs/rules/UnsynchronizedStaticDateFormatter.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# UnsynchronizedStaticDateFormatter
-**Category:** `pmd`
-**Rule Key:** `pmd:UnsynchronizedStaticDateFormatter`
-> :warning: This rule is **deprecated** in favour of [S2156](https://rules.sonarsource.com/java/RSPEC-2156).
-
------
-
-SimpleDateFormat is not synchronized. Sun recomends separate format instances for each thread. If multiple threads must access a static formatter, the formatter must be synchronized either on method or block level.
diff --git a/docs/rules/UnusedFormalParameter.md b/docs/rules/UnusedFormalParameter.md
deleted file mode 100644
index 91a07e2d..00000000
--- a/docs/rules/UnusedFormalParameter.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# UnusedFormalParameter
-**Category:** `pmd`
-**Rule Key:** `pmd:UnusedFormalParameter`
-> :warning: This rule is **deprecated** in favour of [S1172](https://rules.sonarsource.com/java/RSPEC-1172).
-
------
-
-
-**Rule Key:** `pmd:UnusedImports`
-> :warning: This rule is **deprecated** in favour of `squid:UselessImportCheck`.
-
------
-
-Avoid unused import statements. Example :
-
-// this is bad
-import java.io.File;
-public class Foo {}
-
diff --git a/docs/rules/UnusedImportsWithTypeResolution.md b/docs/rules/UnusedImportsWithTypeResolution.md
deleted file mode 100644
index 247cb8c2..00000000
--- a/docs/rules/UnusedImportsWithTypeResolution.md
+++ /dev/null
@@ -1,13 +0,0 @@
-# UnusedImportsWithTypeResolution
-**Category:** `pmd`
-**Rule Key:** `pmd:UnusedImportsWithTypeResolution`
-> :warning: This rule is **deprecated** in favour of `squid:UselessImportCheck`.
-
------
-
-Avoid unused import statements. This rule will find unused on demand imports, i.e. import com.foo.*. Example:
-
-import java.io.*; // not referenced or required
-
-public class Foo {}
-
diff --git a/docs/rules/UnusedLocalVariable.md b/docs/rules/UnusedLocalVariable.md
deleted file mode 100644
index 811774be..00000000
--- a/docs/rules/UnusedLocalVariable.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# UnusedLocalVariable
-**Category:** `pmd`
-**Rule Key:** `pmd:UnusedLocalVariable`
-> :warning: This rule is **deprecated** in favour of [S1481](https://rules.sonarsource.com/java/RSPEC-1481).
-
------
-
-Detects when a local variable is declared and/or assigned, but not used.
diff --git a/docs/rules/UnusedModifier.md b/docs/rules/UnusedModifier.md
deleted file mode 100644
index 8e5aafba..00000000
--- a/docs/rules/UnusedModifier.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# UnusedModifier
-**Category:** `pmd`
-**Rule Key:** `pmd:UnusedModifier`
-
-
------
-
-Fields in interfaces are automatically public static final, and methods are public abstract. Classes or interfaces nested in an interface are automatically public and static (all nested interfaces are automatically static). For historical reasons, modifiers which are implied by the context are accepted by the compiler, but are superfluous.
diff --git a/docs/rules/UnusedNullCheckInEquals.md b/docs/rules/UnusedNullCheckInEquals.md
deleted file mode 100644
index dcb39e69..00000000
--- a/docs/rules/UnusedNullCheckInEquals.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# UnusedNullCheckInEquals
-**Category:** `pmd`
-**Rule Key:** `pmd:UnusedNullCheckInEquals`
-
-
------
-
-After checking an object reference for null, you should invoke equals() on that object rather than passing it to another object's equals() method.
diff --git a/docs/rules/UnusedPrivateField.md b/docs/rules/UnusedPrivateField.md
deleted file mode 100644
index d18b94df..00000000
--- a/docs/rules/UnusedPrivateField.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# UnusedPrivateField
-**Category:** `pmd`
-**Rule Key:** `pmd:UnusedPrivateField`
-> :warning: This rule is **deprecated** in favour of [S1068](https://rules.sonarsource.com/java/RSPEC-1068).
-
------
-
-Detects when a private field is declared and/or assigned a value, but not used.
diff --git a/docs/rules/UnusedPrivateMethod.md b/docs/rules/UnusedPrivateMethod.md
deleted file mode 100644
index 831bfe72..00000000
--- a/docs/rules/UnusedPrivateMethod.md
+++ /dev/null
@@ -1,12 +0,0 @@
-# UnusedPrivateMethod
-**Category:** `pmd`
-**Rule Key:** `pmd:UnusedPrivateMethod`
-> :warning: This rule is **deprecated** in favour of `squid:UnusedPrivateMethod`.
-
------
-
-
-**Rule Key:** `pmd:UseArrayListInsteadOfVector`
-> :warning: This rule is **deprecated** in favour of [S1149](https://rules.sonarsource.com/java/RSPEC-1149).
-
------
-
-ArrayList is a much better Collection implementation than Vector.
diff --git a/docs/rules/UseArraysAsList.md b/docs/rules/UseArraysAsList.md
deleted file mode 100644
index 304d069a..00000000
--- a/docs/rules/UseArraysAsList.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# UseArraysAsList
-**Category:** `pmd`
-**Rule Key:** `pmd:UseArraysAsList`
-
-
------
-
-The class java.util.Arrays has a asList method that should be use when you want to create a new List from an array of objects. It is faster than executing a loop to cpy all the elements of the array one by one
diff --git a/docs/rules/UseAssertEqualsInsteadOfAssertTrue.md b/docs/rules/UseAssertEqualsInsteadOfAssertTrue.md
deleted file mode 100644
index 376c962c..00000000
--- a/docs/rules/UseAssertEqualsInsteadOfAssertTrue.md
+++ /dev/null
@@ -1,17 +0,0 @@
-# UseAssertEqualsInsteadOfAssertTrue
-**Category:** `pmd-unit-tests`
-**Rule Key:** `pmd-unit-tests:UseAssertEqualsInsteadOfAssertTrue`
-
-
------
-
-This rule detects JUnit assertions in object equality. These assertions should be made by more specific methods, like assertEquals.
-
-public class FooTest extends TestCase {
- void testCode() {
- Object a, b;
-
- assertTrue(a.equals(b)); // violation
- assertEquals("a should equals b", a, b); // good usage
- }
-}
diff --git a/docs/rules/UseAssertNullInsteadOfAssertTrue.md b/docs/rules/UseAssertNullInsteadOfAssertTrue.md
deleted file mode 100644
index fef99aa2..00000000
--- a/docs/rules/UseAssertNullInsteadOfAssertTrue.md
+++ /dev/null
@@ -1,20 +0,0 @@
-# UseAssertNullInsteadOfAssertTrue
-**Category:** `pmd-unit-tests`
-**Rule Key:** `pmd-unit-tests:UseAssertNullInsteadOfAssertTrue`
-
-
------
-
-This rule detects JUnit assertions in object references equality. These assertions should be made by more specific methods, like assertNull, assertNotNull.
-
-public class FooTest extends TestCase {
- void testCode() {
- Object a = doSomething();
-
- assertTrue(a==null); // violation
- assertNull(a); // good usage
- assertTrue(a != null); // violation
- assertNotNull(a); // good usage
- }
-}
-
diff --git a/docs/rules/UseAssertSameInsteadOfAssertTrue.md b/docs/rules/UseAssertSameInsteadOfAssertTrue.md
deleted file mode 100644
index 010e55f4..00000000
--- a/docs/rules/UseAssertSameInsteadOfAssertTrue.md
+++ /dev/null
@@ -1,18 +0,0 @@
-# UseAssertSameInsteadOfAssertTrue
-**Category:** `pmd-unit-tests`
-**Rule Key:** `pmd-unit-tests:UseAssertSameInsteadOfAssertTrue`
-
-
------
-
-This rule detects JUnit assertions in object references equality. These assertions should be made by more specific methods, like assertSame, assertNotSame.
-
-public class FooTest extends TestCase {
- void testCode() {
- Object a, b;
-
- assertTrue(a==b); // violation
- assertSame(a, b); // good usage
- }
-}
-
diff --git a/docs/rules/UseAssertTrueInsteadOfAssertEquals.md b/docs/rules/UseAssertTrueInsteadOfAssertEquals.md
deleted file mode 100644
index 2623037e..00000000
--- a/docs/rules/UseAssertTrueInsteadOfAssertEquals.md
+++ /dev/null
@@ -1,21 +0,0 @@
-# UseAssertTrueInsteadOfAssertEquals
-**Category:** `pmd-unit-tests`
-**Rule Key:** `pmd-unit-tests:UseAssertTrueInsteadOfAssertEquals`
-
-
------
-
-When asserting a value is the same as a boolean literal, use assertTrue/assertFalse, instead of assertEquals. Example:
-
-public class MyTestCase extends TestCase {
- public void testMyCase() {
- boolean myVar = true;
- // Ok
- assertTrue("myVar is true", myVar);
- // Bad
- assertEquals("myVar is true", true, myVar);
- // Bad
- assertEquals("myVar is false", false, myVar);
- }
-}
-
diff --git a/docs/rules/UseCollectionIsEmpty.md b/docs/rules/UseCollectionIsEmpty.md
deleted file mode 100644
index 11eea16e..00000000
--- a/docs/rules/UseCollectionIsEmpty.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# UseCollectionIsEmpty
-**Category:** `pmd`
-**Rule Key:** `pmd:UseCollectionIsEmpty`
-> :warning: This rule is **deprecated** in favour of [S1155](https://rules.sonarsource.com/java/RSPEC-1155).
-
------
-
-The isEmpty() method on java.util.Collection is provided to see if a collection has any elements. Comparing the value of size() to 0 merely duplicates existing behavior.
diff --git a/docs/rules/UseConcurrentHashMap.md b/docs/rules/UseConcurrentHashMap.md
deleted file mode 100644
index a6cb515f..00000000
--- a/docs/rules/UseConcurrentHashMap.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# UseConcurrentHashMap
-**Category:** `pmd`
-**Rule Key:** `pmd:UseConcurrentHashMap`
-
-
------
-
-Since Java5 brought a new implementation of the Map interface, specially designed for concurrent application.
diff --git a/docs/rules/UseCorrectExceptionLogging.md b/docs/rules/UseCorrectExceptionLogging.md
deleted file mode 100644
index 0d2d7637..00000000
--- a/docs/rules/UseCorrectExceptionLogging.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# UseCorrectExceptionLogging
-**Category:** `pmd`
-**Rule Key:** `pmd:UseCorrectExceptionLogging`
-> :warning: This rule is **deprecated** in favour of [S1166](https://rules.sonarsource.com/java/RSPEC-1166).
-
------
-
-To make sure the full stacktrace is printed out, use the logging statement with 2 arguments: a String and a Throwable.
diff --git a/docs/rules/UseEqualsToCompareStrings.md b/docs/rules/UseEqualsToCompareStrings.md
deleted file mode 100644
index 62835ade..00000000
--- a/docs/rules/UseEqualsToCompareStrings.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# UseEqualsToCompareStrings
-**Category:** `pmd`
-**Rule Key:** `pmd:UseEqualsToCompareStrings`
-> :warning: This rule is **deprecated** in favour of `squid:StringEqualityComparisonCheck`, [S1698](https://rules.sonarsource.com/java/RSPEC-1698).
-
------
-
-Using "==" or "!=" to compare strings only works if intern version is used on both sides.
diff --git a/docs/rules/UseIndexOfChar.md b/docs/rules/UseIndexOfChar.md
deleted file mode 100644
index 11ccfd02..00000000
--- a/docs/rules/UseIndexOfChar.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# UseIndexOfChar
-**Category:** `pmd`
-**Rule Key:** `pmd:UseIndexOfChar`
-
-
------
-
-Use String.indexOf(char) when checking for the index of a single character; it executes faster.
diff --git a/docs/rules/UseLocaleWithCaseConversions.md b/docs/rules/UseLocaleWithCaseConversions.md
deleted file mode 100644
index a13a6fdb..00000000
--- a/docs/rules/UseLocaleWithCaseConversions.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# UseLocaleWithCaseConversions
-**Category:** `pmd`
-**Rule Key:** `pmd:UseLocaleWithCaseConversions`
-
-
------
-
-When doing a String.toLowerCase()/toUpperCase() call, use a Locale. This avoids problems with certain locales, i.e. Turkish.
diff --git a/docs/rules/UseNotifyAllInsteadOfNotify.md b/docs/rules/UseNotifyAllInsteadOfNotify.md
deleted file mode 100644
index 111de85a..00000000
--- a/docs/rules/UseNotifyAllInsteadOfNotify.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# UseNotifyAllInsteadOfNotify
-**Category:** `pmd`
-**Rule Key:** `pmd:UseNotifyAllInsteadOfNotify`
-> :warning: This rule is **deprecated** in favour of [S2446](https://rules.sonarsource.com/java/RSPEC-2446).
-
------
-
-Thread.notify() awakens a thread monitoring the object. If more than one thread is monitoring, then only one is chosen. The thread chosen is arbitrary; thus it's usually safer to call notifyAll() instead.
diff --git a/docs/rules/UseObjectForClearerAPI.md b/docs/rules/UseObjectForClearerAPI.md
deleted file mode 100644
index c759da8e..00000000
--- a/docs/rules/UseObjectForClearerAPI.md
+++ /dev/null
@@ -1,28 +0,0 @@
-# UseObjectForClearerAPI
-**Category:** `pmd`
-**Rule Key:** `pmd:UseObjectForClearerAPI`
-> :warning: This rule is **deprecated** in favour of [S00107](https://rules.sonarsource.com/java/RSPEC-107).
-
------
-
-When you write a public method, you should be thinking in terms of an API. If your method is public, it means other class
-will use it, therefore, you want (or need) to offer a comprehensive and evolutive API. If you pass a lot of information
-as a simple series of Strings, you may think of using an Object to represent all those information. You'll get a simplier
-API (such as doWork(Workload workload), rather than a tedious series of Strings) and more importantly, if you need at some
-point to pass extra data, you'll be able to do so by simply modifying or extending Workload without any modification to
-your API. Example:
-
-public class MyClass {
- public void connect(String username,
- String pssd,
- String databaseName,
- String databaseAdress)
- // Instead of those parameters object
- // would ensure a cleaner API and permit
- // to add extra data transparently (no code change):
- // void connect(UserData data);
- {
-
- }
-}
-
diff --git a/docs/rules/UseProperClassLoader.md b/docs/rules/UseProperClassLoader.md
deleted file mode 100644
index 5e3ba4f0..00000000
--- a/docs/rules/UseProperClassLoader.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# UseProperClassLoader
-**Category:** `pmd`
-**Rule Key:** `pmd:UseProperClassLoader`
-
-
------
-
-In J2EE getClassLoader() might not work as expected. Use Thread.currentThread().getContextClassLoader() instead.
diff --git a/docs/rules/UseStringBufferForStringAppends.md b/docs/rules/UseStringBufferForStringAppends.md
deleted file mode 100644
index d971b692..00000000
--- a/docs/rules/UseStringBufferForStringAppends.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# UseStringBufferForStringAppends
-**Category:** `pmd`
-**Rule Key:** `pmd:UseStringBufferForStringAppends`
-
-
------
-
-Finds usages of += for appending strings.
diff --git a/docs/rules/UseStringBufferLength.md b/docs/rules/UseStringBufferLength.md
deleted file mode 100644
index a5453b9e..00000000
--- a/docs/rules/UseStringBufferLength.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# UseStringBufferLength
-**Category:** `pmd`
-**Rule Key:** `pmd:UseStringBufferLength`
-
-
------
-
-Use StringBuffer.length() to determine StringBuffer length rather than using StringBuffer.toString().equals() or StringBuffer.toString().length() ==.
diff --git a/docs/rules/UseUtilityClass.md b/docs/rules/UseUtilityClass.md
deleted file mode 100644
index 94dc3069..00000000
--- a/docs/rules/UseUtilityClass.md
+++ /dev/null
@@ -1,11 +0,0 @@
-# UseUtilityClass
-**Category:** `pmd`
-**Rule Key:** `pmd:UseUtilityClass`
-> :warning: This rule is **deprecated** in favour of [S1118](https://rules.sonarsource.com/java/RSPEC-1118).
-
------
-
-For classes that only have static methods, consider making them utility classes.
-Note that this doesn't apply to abstract classes, since their subclasses may well include non-static methods.
-Also, if you want this class to be a utility class, remember to add a private constructor to prevent instantiation.
-(Note, that this use was known before PMD 5.1.0 as UseSingleton).
diff --git a/docs/rules/UseVarargs.md b/docs/rules/UseVarargs.md
deleted file mode 100644
index 8ea5b5f1..00000000
--- a/docs/rules/UseVarargs.md
+++ /dev/null
@@ -1,21 +0,0 @@
-# UseVarargs
-**Category:** `pmd`
-**Rule Key:** `pmd:UseVarargs`
-
-
------
-
-Java 5 introduced the varargs parameter declaration for methods and constructors. This syntactic
-sugar provides flexibility for users of these methods and constructors, allowing them to avoid
-having to deal with the creation of an array. Example:
-
-public class Foo {
- public void foo(String s, Object[] args) {
- // Do something here...
- }
-
- public void bar(String s, Object... args) {
- // Ahh, varargs tastes much better...
- }
-}
-
diff --git a/docs/rules/UselessOperationOnImmutable.md b/docs/rules/UselessOperationOnImmutable.md
deleted file mode 100644
index d2699060..00000000
--- a/docs/rules/UselessOperationOnImmutable.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# UselessOperationOnImmutable
-**Category:** `pmd`
-**Rule Key:** `pmd:UselessOperationOnImmutable`
-
-
------
-
-An operation on an Immutable object (BigDecimal or BigInteger) won't change the object itself. The result of the operation is a new object. Therefore, ignoring the operation result is an error.
diff --git a/docs/rules/UselessOverridingMethod.md b/docs/rules/UselessOverridingMethod.md
deleted file mode 100644
index 89e98839..00000000
--- a/docs/rules/UselessOverridingMethod.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# UselessOverridingMethod
-**Category:** `pmd`
-**Rule Key:** `pmd:UselessOverridingMethod`
-> :warning: This rule is **deprecated** in favour of [S1185](https://rules.sonarsource.com/java/RSPEC-1185).
-
------
-
-The overriding method merely calls the same method defined in a superclass
diff --git a/docs/rules/UselessParentheses.md b/docs/rules/UselessParentheses.md
deleted file mode 100644
index 684fab63..00000000
--- a/docs/rules/UselessParentheses.md
+++ /dev/null
@@ -1,21 +0,0 @@
-# UselessParentheses
-**Category:** `pmd`
-**Rule Key:** `pmd:UselessParentheses`
-> :warning: This rule is **deprecated** in favour of `squid:UselessParenthesesCheck`.
-
------
-
-Useless parentheses should be removed. Example:
-
-public class Foo {
-
- private int _bar1;
- private Integer _bar2;
-
- public void setBar(int n) {
- _bar1 = Integer.valueOf((n)); // here
- _bar2 = (n); // and here
- }
-
-}
-
diff --git a/docs/rules/UselessQualifiedThis.md b/docs/rules/UselessQualifiedThis.md
deleted file mode 100644
index 1e8ba96d..00000000
--- a/docs/rules/UselessQualifiedThis.md
+++ /dev/null
@@ -1,37 +0,0 @@
-# UselessQualifiedThis
-**Category:** `pmd`
-**Rule Key:** `pmd:UselessQualifiedThis`
-
-
------
-
-
-public class Foo {
- final Foo otherFoo = Foo.this; // use "this" directly
-
- public void doSomething() {
- final Foo anotherFoo = Foo.this; // use "this" directly
- }
-
- private ActionListener returnListener() {
- return new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- doSomethingWithQualifiedThis(Foo.this); // This is fine
- }
- };
- }
-
- private class Foo3 {
- final Foo myFoo = Foo.this; // This is fine
- }
-
- private class Foo2 {
- final Foo2 myFoo2 = Foo2.this; // Use "this" direclty
- }
-}
-
diff --git a/docs/rules/UselessStringValueOf.md b/docs/rules/UselessStringValueOf.md
deleted file mode 100644
index b454af70..00000000
--- a/docs/rules/UselessStringValueOf.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# UselessStringValueOf
-**Category:** `pmd`
-**Rule Key:** `pmd:UselessStringValueOf`
-> :warning: This rule is **deprecated** in favour of [S1153](https://rules.sonarsource.com/java/RSPEC-1153).
-
------
-
-No need to call String.valueOf to append to a string; just use the valueOf() argument directly.
diff --git a/docs/rules/VariableNamingConventions.md b/docs/rules/VariableNamingConventions.md
deleted file mode 100644
index ac3ad558..00000000
--- a/docs/rules/VariableNamingConventions.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# VariableNamingConventions
-**Category:** `pmd`
-**Rule Key:** `pmd:VariableNamingConventions`
-> :warning: This rule is **deprecated** in favour of [S00115](https://rules.sonarsource.com/java/RSPEC-115), [S00116](https://rules.sonarsource.com/java/RSPEC-116).
-
------
-
-A variable naming conventions rule - customize this to your liking. Currently, it checks for final variables that should be fully capitalized and non-final variables that should not include underscores.
diff --git a/docs/rules/WhileLoopsMustUseBraces.md b/docs/rules/WhileLoopsMustUseBraces.md
deleted file mode 100644
index f84b78fe..00000000
--- a/docs/rules/WhileLoopsMustUseBraces.md
+++ /dev/null
@@ -1,10 +0,0 @@
-# WhileLoopsMustUseBraces
-**Category:** `pmd`
-**Rule Key:** `pmd:WhileLoopsMustUseBraces`
-> :warning: This rule is **deprecated** in favour of [S00121](https://rules.sonarsource.com/java/RSPEC-121).
-
------
-
-
-**Rule Key:** `pmd:XPathRule`
-
-
------
-
-PMD provides a very handy method for creating new rules by writing an XPath query. When the XPath query finds a match, a violation is created.
-Let's take a simple example: assume we have a Factory class that must be always declared final.
-We'd like to report a violation each time a declaration of Factory is not declared final. Consider the following class:
-
-public class a {
- Factory f1;
-
- void myMethod() {
- Factory f2;
- int a;
- }
-}
-
-The following expression does the magic we need:
-
-//VariableDeclarator
- [../Type/ReferenceType/ClassOrInterfaceType
- [@Image = 'Factory'] and ..[@Final='false']]
-
-See the XPath rule
- tutorial for more information.
-
-Example
+ public abstract class Foo {
+ void int method1() { ... }
+ void int method2() { ... }
+ // consider using abstract methods or removing
+ // the abstract modifier and adding protected constructors
+ }
Alternative rule: java:S1694
+]]> +If an abstract class does not provide any methods, it may be acting as a simple data container +that is not meant to be instantiated. In this case, it is probably better to use a private or +protected constructor in order to prevent instantiation than make the class misleadingly abstract.
+ public abstract class Example {
+ String field;
+ int otherField;
+ }
+Alternative rule: java:S1694
+]]>Instantiation by way of private constructors from outside the constructor's class often causes the +generation of an accessor. A factory method, or non-privatization of the constructor can eliminate this +situation. The generated class file is actually an interface. It gives the accessing class the ability +to invoke a new hidden package scope constructor that takes the interface as a supplementary parameter. +This turns a private constructor effectively into one with package scope, and is challenging to discern.
+Note: This rule is only executed for Java 10 or lower. +Since Java 11, JEP 181: Nest-Based Access Control has been implemented. This +means that in Java 11 and above accessor classes are not generated anymore.
+ public class Outer {
+ void method(){
+ Inner ic = new Inner();//Causes generation of accessor class
+ }
+ public class Inner {
+ private Inner(){}
+ }
+ }
+]]>{0}
without a synthetic accessor method
+When accessing private fields / methods from another class, the Java compiler will generate accessor methods +with package-private visibility. This adds overhead, and to the dex method count on Android. This situation can +be avoided by changing the visibility of the field / method from private to package-private.
+Note: This rule is only executed for Java 10 or lower. +Since Java 11, JEP 181: Nest-Based Access Control has been implemented. This +means that in Java 11 and above accessor classes are not generated anymore.
+ public class OuterClass {
+ private int counter;
+ /* package */ int id;
+
+ public class InnerClass {
+ InnerClass() {
+ OuterClass.this.counter++; // wrong accessor method will be generated
+ }
+
+ public int getOuterClassId() {
+ return OuterClass.this.id; // id is package-private, no accessor method needed
+ }
+ }
+ }
+]]>The conversion of literals to strings by concatenating them with empty strings is inefficient.
+It is much better to use one of the type-specific toString()
methods instead or String.valueOf()
.
String s = "" + 123; // inefficient
+ String t = Integer.toString(456); // preferred approach
+]]>Avoid concatenating characters as strings in StringBuffer/StringBuilder.append methods.
+ StringBuffer sb = new StringBuffer();
+ sb.append("a"); // avoid this
+
+ StringBuffer sb = new StringBuffer();
+ sb.append('a'); // use this instead
+]]>{0}
' is stored directly.
+Constructors and methods receiving arrays should clone objects and store the copy. +This prevents future changes from the user from affecting the original array.
+ public class Foo {
+ private String [] x;
+ public void foo (String [] param) {
+ // Don't do this, make a copy of the array at least
+ this.x=param;
+ }
+ }
+Alternative rule: java:S2384
+]]>Avoid assignments in operands; this can make code more complicated and harder to read.
+ public void bar() {
+ int x = 2;
+ if ((x = getX()) == 3) {
+ System.out.println("3!");
+ }
+ }
+Alternative rule: java:S1121
+]]>{0}
' in a constructor.
+Identifies a possible unsafe usage of a static field.
+ public class StaticField {
+ static int x;
+ public FinalFields(int y) {
+ x = y; // unsafe
+ }
+ }
+]]>Each non-static class should declare at least one constructor. +Classes with solely static members are ignored, refer to UseUtilityClassRule to detect those.
+ public class Foo {
+ // missing constructor
+ public void doSomething() { ... }
+ public void doOtherThing { ... }
+ }
+Alternative rules: java:S1118, java:S1258
+]]>Methods such as getDeclaredConstructors()
, getDeclaredMethods()
, and getDeclaredFields()
also
+return private constructors, methods and fields. These can be made accessible by calling setAccessible(true)
.
+This gives access to normally protected data which violates the principle of encapsulation.
This rule detects calls to setAccessible
and finds possible accessibility alterations.
+If the call to setAccessible
is wrapped within a PrivilegedAction
, then the access alteration
+is assumed to be deliberate and is not reported.
Note that with Java 17 the Security Manager, which is used for PrivilegedAction
execution,
+is deprecated: JEP 411: Deprecate the Security Manager for Removal.
+For future-proof code, deliberate access alteration should be suppressed using the usual
+suppression methods (e.g. by using @SuppressWarnings
annotation).
import java.lang.reflect.Constructor;
+ import java.lang.reflect.Field;
+ import java.lang.reflect.Method;
+ import java.security.AccessController;
+ import java.security.PrivilegedAction;
+
+ public class Violation {
+ private void invalidSetAccessCalls() throws NoSuchMethodException, SecurityException {
+ Constructor<?> constructor = this.getClass().getDeclaredConstructor(String.class);
+ // call to forbidden setAccessible
+ constructor.setAccessible(true);
+
+ Method privateMethod = this.getClass().getDeclaredMethod("aPrivateMethod");
+ // call to forbidden setAccessible
+ privateMethod.setAccessible(true);
+
+ // deliberate accessibility alteration
+ String privateField = AccessController.doPrivileged(new PrivilegedAction<String>() {
+ @Override
+ public String run() {
+ try {
+ Field field = Violation.class.getDeclaredField("aPrivateField");
+ field.setAccessible(true);
+ return (String) field.get(null);
+ } catch (ReflectiveOperationException | SecurityException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ });
+ }
+ }
+]]>Instead of manually copying data between two arrays, use the more efficient Arrays.copyOf
+or System.arraycopy
method instead.
To copy only part of the array, use Arrays.copyOfRange
or System.arraycopy
.
If you want to copy/move elements inside the _same_ array (e.g. shift the elements), use System.arraycopy
.
class Scratch {
+ void copy_a_to_b() {
+ int[] a = new int[10];
+ int[] b = new int[10];
+ for (int i = 0; i < a.length; i++) {
+ b[i] = a[i];
+ }
+ // equivalent
+ b = Arrays.copyOf(a, a.length);
+ // equivalent
+ System.arraycopy(a, 0, b, 0, a.length);
+
+ int[] c = new int[10];
+ // this will not trigger the rule
+ for (int i = 0; i < c.length; i++) {
+ b[i] = a[c[i]];
+ }
+ }
+ }
+ class Scratch {
+ void shift_left(int[] a) {
+ for (int i = 0; i < a.length - 1; i++) {
+ a[i] = a[i + 1];
+ }
+ // equivalent
+ System.arraycopy(a, 1, a, 0, a.length - 1);
+ }
+ void shift_right(int[] a) {
+ for (int i = a.length - 1; i > 0; i--) {
+ a[i] = a[i - 1];
+ }
+ // equivalent
+ System.arraycopy(a, 0, a, 1, a.length - 1);
+ }
+ }
+]]>Use of the term assert
will conflict with newer versions of Java since it is a reserved word.
Since Java 1.4, the token assert
became a reserved word and using it as an identifier will
+result in a compilation failure for Java 1.4 and later. This rule is therefore only useful
+for old Java code before Java 1.4. It can be used to identify problematic code prior to a Java update.
public class A {
+ public class Foo {
+ String assert = "foo";
+ }
+ }
+Alternative rule: java:S1190
+]]>Using a branching statement as the last part of a loop may be a bug, and/or is confusing. +Ensure that the usage is not a bug, or consider using another approach.
+ // unusual use of branching statement in a loop
+ for (int i = 0; i < 10; i++) {
+ if (i*i <= 25) {
+ continue;
+ }
+ break;
+ }
+
+ // this makes more sense...
+ for (int i = 0; i < 10; i++) {
+ if (i*i > 25) {
+ break;
+ }
+ }
+]]>Problem: java.util.Calendar
is a heavyweight object and expensive to create. It should only be used, if
+calendar calculations are needed.
Solution: Use new Date()
, Java 8+ java.time.LocalDateTime.now()
or ZonedDateTime.now()
.
import java.time.LocalDateTime;
+ import java.util.Calendar;
+ import java.util.Date;
+
+ public class DateStuff {
+ private Date bad1() {
+ return Calendar.getInstance().getTime(); // now
+ }
+ private Date good1a() {
+ return new Date(); // now
+ }
+ private LocalDateTime good1b() {
+ return LocalDateTime.now();
+ }
+ private long bad2() {
+ return Calendar.getInstance().getTimeInMillis();
+ }
+ private long good2() {
+ return System.currentTimeMillis();
+ }
+ }
+]]>The method Object.finalize() is called by the garbage collector on an object when garbage collection determines +that there are no more references to the object. It should not be invoked by application logic.
+Note that Oracle has declared Object.finalize() as deprecated since JDK 9.
+ void foo() {
+ Bar b = new Bar();
+ b.finalize();
+ }
+]]>Avoid catching generic exceptions such as NullPointerException, RuntimeException, Exception in try-catch block.
+ package com.igate.primitive;
+
+ public class PrimitiveType {
+
+ public void downCastPrimitiveType() {
+ try {
+ System.out.println(" i [" + i + "]");
+ } catch(Exception e) {
+ e.printStackTrace();
+ } catch(RuntimeException e) {
+ e.printStackTrace();
+ } catch(NullPointerException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+Alternative rule: java:S2221
+]]>Code should never throw NullPointerExceptions under normal circumstances. A catch block may hide the +original error, causing other, more subtle problems later on.
+ public class Foo {
+ void bar() {
+ try {
+ // do something
+ } catch (NullPointerException npe) {
+ }
+ }
+ }
+Alternative rule: java:S1696
+]]>Catching Throwable errors is not recommended since its scope is very broad. It includes runtime issues such as +OutOfMemoryError that should be exposed and managed separately.
+ public void bar() {
+ try {
+ // do something
+ } catch (Throwable th) { // should not catch Throwable
+ th.printStackTrace();
+ }
+ }
+Alternative rule: java:S1181
+]]>One might assume that the result of "new BigDecimal(0.1)" is exactly equal to 0.1, but it is actually +equal to .1000000000000000055511151231257827021181583404541015625. +This is because 0.1 cannot be represented exactly as a double (or as a binary fraction of any finite +length). Thus, the long value that is being passed in to the constructor is not exactly equal to 0.1, +appearances notwithstanding.
+The (String) constructor, on the other hand, is perfectly predictable: 'new BigDecimal("0.1")' is +exactly equal to 0.1, as one would expect. Therefore, it is generally recommended that the +(String) constructor be used in preference to this one.
+ BigDecimal bd = new BigDecimal(1.123); // loss of precision, this would trigger the rule
+
+ BigDecimal bd = new BigDecimal("1.123"); // preferred approach
+
+ BigDecimal bd = new BigDecimal(12); // preferred approach, ok for integer values
+Alternative rule: java:S2111
+]]>Avoid creating deeply nested if-then statements since they are harder to read and error-prone to maintain.
+ public class Foo {
+ public void bar(int x, int y, int z) {
+ if (x>y) {
+ if (y>z) {
+ if (z==x) {
+ // !! too deep
+ }
+ }
+ }
+ }
+ }
+Alternative rule: java:S134
+]]>Avoid using dollar signs in variable/method/class/interface names.
+ public class Fo$o { // not a recommended name
+ }
+Alternative rules: java:S114, java:S115, java:S116, java:S117
+]]>{0}
appears {1}
times in this file; the first occurrence is on line {2}
+Code containing duplicate String literals can usually be improved by declaring the String as a constant field.
+ private void bar() {
+ buz("Howdy");
+ buz("Howdy");
+ buz("Howdy");
+ buz("Howdy");
+ }
+ private void buz(String x) {}
+Alternative rule: java:S1192
+]]>Use of the term enum
will conflict with newer versions of Java since it is a reserved word.
Since Java 1.5, the token enum
became a reserved word and using it as an identifier will
+result in a compilation failure for Java 1.5 and later. This rule is therefore only useful
+for old Java code before Java 1.5. It can be used to identify problematic code prior to a Java update.
public class A {
+ public class Foo {
+ String enum = "foo";
+ }
+ }
+Alternative rule: java:S1190
+]]>{0}
has the same name as a method
+It can be confusing to have a field name with the same name as a method. While this is permitted, +having information (field) and actions (method) is not clear naming. Developers versed in +Smalltalk often prefer this approach as the methods denote accessor methods.
+ public class Foo {
+ Object bar;
+ // bar is data or an action or both?
+ void bar() {
+ }
+ }
+Alternative rule: java:S1845
+]]>It is somewhat confusing to have a field name matching the declaring type name. +This probably means that type and/or field names should be chosen more carefully.
+ public class Foo extends Bar {
+ int foo; // There is probably a better name that can be used
+ }
+ public interface Operation {
+ int OPERATION = 1; // There is probably a better name that can be used
+ }
+Alternative rule: java:S1700
+]]>The FileInputStream and FileOutputStream classes contains a finalizer method which will cause garbage +collection pauses. +See JDK-8080225 for details.
+The FileReader and FileWriter constructors instantiate FileInputStream and FileOutputStream, +again causing garbage collection issues while finalizer methods are called.
+Files.newInputStream(Paths.get(fileName))
instead of new FileInputStream(fileName)
.Files.newOutputStream(Paths.get(fileName))
instead of new FileOutputStream(fileName)
.Files.newBufferedReader(Paths.get(fileName))
instead of new FileReader(fileName)
.Files.newBufferedWriter(Paths.get(fileName))
instead of new FileWriter(fileName)
.Please note, that the java.nio
API does not throw a FileNotFoundException
anymore, instead
+it throws a NoSuchFileException
. If your code dealt explicitly with a FileNotFoundException
,
+then this needs to be adjusted. Both exceptions are subclasses of IOException
, so catching
+that one covers both.
// these instantiations cause garbage collection pauses, even if properly closed
+
+ FileInputStream fis = new FileInputStream(fileName);
+ FileOutputStream fos = new FileOutputStream(fileName);
+ FileReader fr = new FileReader(fileName);
+ FileWriter fw = new FileWriter(fileName);
+
+ // the following instantiations help prevent Garbage Collection pauses, no finalization
+
+ try(InputStream is = Files.newInputStream(Paths.get(fileName))) {
+ }
+ try(OutputStream os = Files.newOutputStream(Paths.get(fileName))) {
+ }
+ try(BufferedReader br = Files.newBufferedReader(Paths.get(fileName), StandardCharsets.UTF_8)) {
+ }
+ try(BufferedWriter wr = Files.newBufferedWriter(Paths.get(fileName), StandardCharsets.UTF_8)) {
+ }
+]]>Each caught exception type should be handled in its own catch clause.
+ try { // Avoid this
+ // do something
+ } catch (Exception ee) {
+ if (ee instanceof IOException) {
+ cleanup();
+ }
+ }
+
+ try { // Prefer this:
+ // do something
+ } catch (IOException ee) {
+ cleanup();
+ }
+Alternative rule: java:S1193
+]]>New objects created within loops should be checked to see if they can created outside them and reused.
+ public class Something {
+ public static void main( String as[] ) {
+ for (int i = 0; i < 10; i++) {
+ Foo f = new Foo(); // Avoid this whenever you can it's really expensive
+ }
+ }
+ }
+]]>Avoid using hard-coded literals in conditional statements. By declaring them as static variables +or private members with descriptive names maintainability is enhanced. By default, the literals "-1" and "0" are ignored. +More exceptions can be defined with the property "ignoreMagicNumbers".
+The rule doesn't consider deeper expressions by default, but this can be enabled via the property ignoreExpressions
.
+With this property set to false, if-conditions like i == 1 + 5
are reported as well. Note that in that case,
+the property ignoreMagicNumbers is not taken into account, if there are multiple literals involved in such an expression.
private static final int MAX_NUMBER_OF_REQUESTS = 10;
+
+ public void checkRequests() {
+
+ if (i == 10) { // magic number, buried in a method
+ doSomething();
+ }
+
+ if (i == MAX_NUMBER_OF_REQUESTS) { // preferred approach
+ doSomething();
+ }
+
+ if (aString.indexOf('.') != -1) {} // magic number -1, by default ignored
+ if (aString.indexOf('.') >= 0) { } // alternative approach
+
+ if (aDouble > 0.0) {} // magic number 0.0
+ if (aDouble >= Double.MIN_VALUE) {} // preferred approach
+
+ // with rule property "ignoreExpressions" set to "false"
+ if (i == pos + 5) {} // violation: magic number 5 within an (additive) expression
+ if (i == pos + SUFFIX_LENGTH) {} // preferred approach
+ if (i == 5 && "none".equals(aString)) {} // 2 violations: magic number 5 and literal "none"
+ }
+Alternative rule: java:S109
+]]>Statements in a catch block that invoke accessors on the exception without using the information +only add to code size. Either remove the invocation, or use the return result.
+ public void bar() {
+ try {
+ // do something
+ } catch (SomeException se) {
+ se.getMessage();
+ }
+ }
+Alternative rule: java:S1166
+]]>Declaring a MessageDigest instance as a field make this instance directly available to multiple threads. + Such sharing of MessageDigest instances should be avoided if possible since it leads to wrong results + if the access is not synchronized correctly. + Just create a new instance and use it locally, where you need it. + Creating a new instance is easier than synchronizing access to a shared instance.
+ import java.security.MessageDigest;
+ public class AvoidMessageDigestFieldExample {
+ private final MessageDigest sharedMd;
+ public AvoidMessageDigestFieldExample() throws Exception {
+ sharedMd = MessageDigest.getInstance("SHA-256");
+ }
+ public byte[] calculateHashShared(byte[] data) {
+ // sharing a MessageDigest like this without synchronizing access
+ // might lead to wrong results
+ sharedMd.reset();
+ sharedMd.update(data);
+ return sharedMd.digest();
+ }
+
+ // better
+ public byte[] calculateHash(byte[] data) throws Exception {
+ MessageDigest md = MessageDigest.getInstance("SHA-256");
+ md.update(data);
+ return md.digest();
+ }
+ }
+]]>The use of multiple unary operators may be problematic, and/or confusing. +Ensure that the intended usage is not a bug, or consider simplifying the expression.
+ // These are typo bugs, or at best needlessly complex and confusing:
+ int i = - -1;
+ int j = + - +1;
+ int z = ~~2;
+ boolean b = !!true;
+ boolean c = !!!true;
+
+ // These are better:
+ int i = 1;
+ int j = -1;
+ int z = 2;
+ boolean b = true;
+ boolean c = false;
+
+ // And these just make your brain hurt:
+ int i = ~-2;
+ int j = -~7;
+Alternative rule: java:S881
+]]>Avoid printStackTrace(); use a logger call instead.
+ class Foo {
+ void bar() {
+ try {
+ // do something
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+ }
+Alternative rule: java:S1148
+]]>Do not use protected fields in final classes since they cannot be subclassed. +Clarify your intent by using private or package access modifiers instead.
+ public final class Bar {
+ private int x;
+ protected int y; // bar cannot be subclassed, so is y really private or package visible?
+ Bar() {}
+ }
+Alternative rule: java:S2156
+]]>Do not use protected methods in most final classes since they cannot be subclassed. This should +only be allowed in final classes that extend other classes with protected methods (whose +visibility cannot be reduced). Clarify your intent by using private or package access modifiers instead.
+ public final class Foo {
+ private int bar() {}
+ protected int baz() {} // Foo cannot be subclassed, and doesn't extend anything, so is baz() really private or package visible?
+ }
+Alternative rule: java:S2156
+]]>{0}
'
+Reassigning exception variables caught in a catch statement should be avoided because of:
+1) If it is needed, multi catch can be easily added and code will still compile.
+2) Following the principle of least surprise we want to make sure that a variable caught in a catch statement +is always the one thrown in a try block.
+ public class Foo {
+ public void foo() {
+ try {
+ // do something
+ } catch (Exception e) {
+ e = new NullPointerException(); // not recommended
+ }
+
+ try {
+ // do something
+ } catch (MyException | ServerException e) {
+ e = new RuntimeException(); // won't compile
+ }
+ }
+ }
+]]>{0}
'
+Reassigning loop variables can lead to hard-to-find bugs. Prevent or limit how these variables can be changed.
+In foreach-loops, configured by the foreachReassign
property:
In for-loops, configured by the forReassign
property:
deny
: Report any reassignment of the loop variable in the loop body. _This is the default._allow
: Don't check the loop variable.firstOnly
: Report any reassignments of the loop variable, except as the first statement in the loop body. _This is useful if some kind of normalization or clean-up of the value before using is permitted, but any other change of the variable is not._deny
: Report any reassignment of the control variable in the loop body. _This is the default._allow
: Don't check the control variable.skip
: Report any reassignments of the control variable, except conditional increments/decrements (++
, --
, +=
, -=
). _This prevents accidental reassignments or unconditional increments of the control variable._ public class Foo {
+ private void foo() {
+ for (String s : listOfStrings()) {
+ s = s.trim(); // OK, when foreachReassign is "firstOnly" or "allow"
+ doSomethingWith(s);
+
+ s = s.toUpper(); // OK, when foreachReassign is "allow"
+ doSomethingElseWith(s);
+ }
+
+ for (int i=0; i < 10; i++) {
+ if (check(i)) {
+ i++; // OK, when forReassign is "skip" or "allow"
+ }
+
+ i = 5; // OK, when forReassign is "allow"
+
+ doSomethingWith(i);
+ }
+ }
+ }
+]]>{0}
'
+Reassigning values to incoming parameters of a method or constructor is not recommended, as this can +make the code more difficult to understand. The code is often read with the assumption that parameter values +don't change and an assignment violates therefore the principle of least astonishment. This is especially a +problem if the parameter is documented e.g. in the method's javadoc and the new content differs from the original +documented content.
+Use temporary local variables instead. This allows you to assign a new name, which makes the code better +understandable.
+Note that this rule considers both methods and constructors. If there are multiple assignments for a formal +parameter, then only the first assignment is reported.
+ public class Hello {
+ private void greet(String name) {
+ name = name.trim();
+ System.out.println("Hello " + name);
+
+ // preferred
+ String trimmedName = name.trim();
+ System.out.println("Hello " + trimmedName);
+ }
+ }
+Alternative rule: java:S1226
+]]>Catch blocks that merely rethrow a caught exception only add to code size and runtime complexity.
+ public void bar() {
+ try {
+ // do something
+ } catch (SomeException se) {
+ throw se;
+ }
+ }
+Alternative rule: java:S1166
+]]>StringBuffers/StringBuilders can grow considerably, and so may become a source of memory leaks +if held within objects with long lifetimes.
+ public class Foo {
+ private StringBuffer buffer; // potential memory leak as an instance variable;
+ }
+Alternative rule: java:S1149
+]]>Method-level synchronization will pin virtual threads and can cause performance problems. Additionally, it can cause +problems when new code is added to the method. Block-level ReentrantLock helps to ensure that only the code that +needs mutual exclusion will be locked.
+ public class Foo {
+ // Try to avoid this:
+ synchronized void foo() {
+ // code, that doesn't need synchronization
+ // ...
+ // code, that requires synchronization
+ if (!sharedData.has("bar")) {
+ sharedData.add("bar");
+ }
+ // more code, that doesn't need synchronization
+ // ...
+ }
+ // Prefer this:
+ Lock instanceLock = new ReentrantLock();
+
+ void bar() {
+ // code, that doesn't need synchronization
+ // ...
+ try {
+ instanceLock.lock(); // or instanceLock.tryLock(long time, TimeUnit unit)
+ if (!sharedData.has("bar")) {
+ sharedData.add("bar");
+ }
+ } finally {
+ instanceLock.unlock();
+ }
+ // more code, that doesn't need synchronization
+ // ...
+ }
+
+ // Try to avoid this for static methods:
+ static synchronized void fooStatic() {
+ }
+
+ // Prefer this:
+ private static Lock CLASS_LOCK = new ReentrantLock();
+
+ static void barStatic() {
+ // code, that doesn't need synchronization
+ // ...
+ try {
+ CLASS_LOCK.lock();
+ // code, that requires synchronization
+ } finally {
+ CLASS_LOCK.unlock();
+ }
+ // more code, that doesn't need synchronization
+ // ...
+ }
+ }
+]]>Synchronization will pin virtual threads and can cause performance problems.
+ public class Foo {
+ // Try to avoid this:
+ void foo() {
+ // code that doesn't need mutual exclusion
+ synchronized(this) {
+ // code that requires mutual exclusion
+ }
+ // more code that doesn't need mutual exclusion
+ }
+ // Prefer this:
+ Lock instanceLock = new ReentrantLock();
+
+ void foo() {
+ // code that doesn't need mutual exclusion
+ try {
+ instanceLock.lock(); // or instanceLock.tryLock(long time, TimeUnit unit)
+ // code that requires mutual exclusion
+ } finally {
+ instanceLock.unlock();
+ }
+ // more code that doesn't need mutual exclusion
+ }
+ }
+]]>Avoid using java.lang.ThreadGroup; although it is intended to be used in a threaded environment +it contains methods that are not thread-safe.
+ public class Bar {
+ void buz() {
+ ThreadGroup tg = new ThreadGroup("My threadgroup");
+ tg = new ThreadGroup(tg, "my thread group");
+ tg = Thread.currentThread().getThreadGroup();
+ tg = System.getSecurityManager().getThreadGroup();
+ }
+ }
+]]>Catch blocks that merely rethrow a caught exception wrapped inside a new instance of the same type only add to +code size and runtime complexity.
+ public void bar() {
+ try {
+ // do something
+ } catch (SomeException se) {
+ // harmless comment
+ throw new SomeException(se);
+ }
+ }
+Alternative rule: java:S1166
+]]>Avoid throwing NullPointerExceptions manually. These are confusing because most people will assume that the +virtual machine threw it. To avoid a method being called with a null parameter, you may consider +using an IllegalArgumentException instead, making it clearly seen as a programmer-initiated exception. +However, there are better ways to handle this:
+>Effective Java, 3rd Edition, Item 72: Favor the use of standard exceptions +> +>Arguably, every erroneous method invocation boils down to an illegal argument or state, +but other exceptions are standardly used for certain kinds of illegal arguments and states. +If a caller passes null in some parameter for which null values are prohibited, convention dictates that +NullPointerException be thrown rather than IllegalArgumentException.
+To implement that, you are encouraged to use java.util.Objects.requireNonNull()
+(introduced in Java 1.7). This method is designed primarily for doing parameter
+validation in methods and constructors with multiple parameters.
Your parameter validation could thus look like the following: +
public class Foo {
+ private String exampleValue;
+
+ void setExampleValue(String exampleValue) {
+ // check, throw and assignment in a single standard call
+ this.exampleValue = Objects.requireNonNull(exampleValue, "exampleValue must not be null!");
+ }
+ }
+ public class Foo {
+ void bar() {
+ throw new NullPointerException();
+ }
+ }
+Alternative rule: java:S1695
+]]>Avoid throwing certain exception types. Rather than throw a raw RuntimeException, Throwable, +Exception, or Error, use a subclassed exception or error instead.
+ public class Foo {
+ public void bar() throws Exception {
+ throw new Exception();
+ }
+ }
+Alternative rule: java:S112
+]]>Reports unchecked exceptions in the throws
clause of a method or constructor.
+Java doesn't force the caller to handle an unchecked exception,
+so it's unnecessary except for documentation. A better practice is to document the
+exceptional cases with a @throws
Javadoc tag, which allows being more descriptive.
public void foo() throws RuntimeException {
+ }
+]]>Application with hard-coded IP addresses can become impossible to deploy in some cases. +Externalizing IP adresses is preferable.
+ public class Foo {
+ private String ip = "127.0.0.1"; // not recommended
+ }
+Alternative rule: java:S1313
+]]>Unnecessary reliance on Java Native Interface (JNI) calls directly reduces application portability +and increases the maintenance burden.
+ public class SomeJNIClass {
+
+ public SomeJNIClass() {
+ System.loadLibrary("nativelib");
+ }
+
+ static {
+ System.loadLibrary("nativelib");
+ }
+
+ public void invalidCallsInMethod() throws SecurityException, NoSuchMethodException {
+ System.loadLibrary("nativelib");
+ }
+ }
+]]>Integer literals should not start with zero since this denotes that the rest of literal will be +interpreted as an octal value.
+ int i = 012; // set i with 10 not 12
+ int j = 010; // set j with 8 not 10
+ k = i * j; // set k with 80 not 120
+Alternative rule: java:S1314
+]]>Use of the keyword 'volatile' is generally used to fine tune a Java application, and therefore, requires +a good expertise of the Java Memory Model. Moreover, its range of action is somewhat misknown. Therefore, +the volatile keyword should not be used for maintenance purpose and portability.
+ public class ThrDeux {
+ private volatile String var1; // not suggested
+ private String var2; // preferred
+ }
+]]>Don't create instances of already existing BigInteger (BigInteger.ZERO
, BigInteger.ONE
),
+for Java 1.5 onwards, BigInteger.TEN and BigDecimal (BigDecimal.ZERO
, BigDecimal.ONE
, BigDecimal.TEN
) and
+for Java 9 onwards BigInteger.TWO
.
BigInteger bi1 = new BigInteger("1"); // reference BigInteger.ONE instead
+ BigInteger bi2 = new BigInteger("0"); // reference BigInteger.ZERO instead
+ BigInteger bi3;
+ bi3 = new BigInteger("0"); // reference BigInteger.ZERO instead
+
+ BigDecimal bd1 = new BigDecimal(0); // reference BigDecimal.ZERO instead
+ BigDecimal bd2 = new BigDecimal("0.") ; // reference BigDecimal.ZERO instead
+ BigDecimal bd3 = new BigDecimal(10); // reference BigDecimal.TEN instead
+]]>Methods that return boolean or Boolean results should be named as predicate statements to denote this. + I.e., 'isReady()', 'hasValues()', 'canCommit()', 'willFail()', etc. Avoid the use of the 'get' prefix for these methods.
+ 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
+]]>The null check is broken since it will throw a NullPointerException itself. +It is likely that you used || instead of && or vice versa.
+ public String bar(String string) {
+ // should be &&
+ if (string!=null || !string.equals(""))
+ return string;
+ // should be ||
+ if (string==null && string.equals(""))
+ return string;
+ }
+Alternative rule: java:S1697
+]]>Super should be called at the start of the method
+ import android.app.Activity;
+ import android.os.Bundle;
+
+ public class DummyActivity extends Activity {
+ public void onCreate(Bundle bundle) {
+ // missing call to super.onCreate(bundle)
+ foo();
+ }
+ }
+]]>It is a good practice to call super() in a constructor. If super() is not called but +another constructor (such as an overloaded constructor) is called, this rule will not report it.
+ public class Foo extends Bar{
+ public Foo() {
+ // call the constructor of Bar
+ super();
+ }
+ public Foo(int code) {
+ // do something with code
+ this();
+ // no problem with this
+ }
+ }
+]]>Super should be called at the end of the method
+ import android.app.Activity;
+
+ public class DummyActivity extends Activity {
+ public void onPause() {
+ foo();
+ // missing call to super.onPause()
+ }
+ }
+]]>Always check the return values of navigation methods (next, previous, first, last) of a ResultSet. +If the value return is 'false', it should be handled properly.
+ Statement stat = conn.createStatement();
+ ResultSet rst = stat.executeQuery("SELECT name FROM person");
+ rst.next(); // what if it returns false? bad form
+ String firstName = rst.getString(1);
+
+ Statement stat = conn.createStatement();
+ ResultSet rst = stat.executeQuery("SELECT name FROM person");
+ if (rst.next()) { // result is properly examined and used
+ String firstName = rst.getString(1);
+ } else {
+ // handle missing data
+ }
+]]>The skip() method may skip a smaller number of bytes than requested. Check the returned value to find out if it was the case or not.
+ public class Foo {
+
+ private FileInputStream _s = new FileInputStream("file");
+
+ public void skip(int n) throws IOException {
+ _s.skip(n); // You are not sure that exactly n bytes are skipped
+ }
+
+ public void skipExactly(int n) throws IOException {
+ while (n != 0) {
+ long skipped = _s.skip(n);
+ if (skipped == 0)
+ throw new EOFException();
+ n -= skipped;
+ }
+ }
+Alternative rule: java:S2674
+]]>When deriving an array of a specific class from your Collection, one should provide an array of
+the same class as the parameter of the toArray()
method. Doing otherwise will result
+in a ClassCastException
.
Collection c = new ArrayList();
+ Integer obj = new Integer(1);
+ c.add(obj);
+
+ // this would trigger the rule (and throw a ClassCastException if executed)
+ Integer[] a = (Integer [])c.toArray();
+
+ // this is fine and will not trigger the rule
+ Integer[] b = (Integer [])c.toArray(new Integer[0]);
+]]>{0}
name '{1}
' doesn't match '{2}
'
+Configurable naming conventions for type declarations. This rule reports + type declarations which do not match the regex that applies to their + specific kind (e.g. enum or interface). Each regex can be configured through + properties.
+By default, this rule uses the standard Java naming convention (Pascal case).
+The rule can detect utility classes and enforce a different naming convention
+ on those. E.g. setting the property utilityClassPattern
to
+ [A-Z][a-zA-Z0-9]+(Utils?|Helper|Constants)
reports any utility class, whose name
+ does not end in "Util(s)", "Helper" or "Constants".
For this rule, a utility class is defined as: a concrete class that does not + inherit from a super class or implement any interface and only has static fields + or methods.
+This rule detects test classes using the following convention: Test classes are top-level classes, that + either inherit from JUnit 3 TestCase or have at least one method annotated with the Test annotations from + JUnit4/5 or TestNG.
+ // This is Pascal case, the recommended naming convention in Java
+ // Note that the default values of this rule don't allow underscores
+ // or accented characters in type names
+ public class FooBar {}
+
+ // You may want abstract classes to be named 'AbstractXXX',
+ // in which case you can customize the regex for abstract
+ // classes to 'Abstract[A-Z]\w+'
+ public abstract class Thing {}
+
+ // This class doesn't respect the convention, and will be flagged
+ public class Éléphant {}
+
+]]>Reports classes that may be made final because they cannot be extended from outside +their compilation unit anyway. This is because all their constructors are private, +so a subclass could not call the super constructor.
+ public class Foo { //Should be final
+ private Foo() { }
+ }
+Alternative rule: java:S2974
+]]>The java manual says "By convention, classes that implement this interface should override +Object.clone (which is protected) with a public method."
+ public class Foo implements Cloneable {
+ @Override
+ protected Object clone() throws CloneNotSupportedException { // Violation, must be public
+ }
+ }
+
+ public class Foo implements Cloneable {
+ @Override
+ protected Foo clone() { // Violation, must be public
+ }
+ }
+
+ public class Foo implements Cloneable {
+ @Override
+ public Object clone() // Ok
+ }
+]]>The method clone() should only be implemented if the class implements the Cloneable interface with the exception of +a final method that only throws CloneNotSupportedException.
+The rule can also detect, if the class implements or extends a Cloneable class.
+ public class MyClass {
+ public Object clone() throws CloneNotSupportedException {
+ return foo;
+ }
+ }
+]]>If a class implements Cloneable
the return type of the method clone()
must be the class name. That way, the caller
+of the clone method doesn't need to cast the returned clone to the correct type.
Note: Such a covariant return type is only possible with Java 1.5 or higher.
+ public class Foo implements Cloneable {
+ @Override
+ protected Object clone() { // Violation, Object must be Foo
+ }
+ }
+
+ public class Foo implements Cloneable {
+ @Override
+ public Foo clone() { //Ok
+ }
+ }
+]]>{0}
object are closed after use
+Ensure that resources (like java.sql.Connection
, java.sql.Statement
, and java.sql.ResultSet
objects
+and any subtype of java.lang.AutoCloseable
) are always closed after use.
+Failing to do so might result in resource leaks.
Note: It suffices to configure the super type, e.g. java.lang.AutoCloseable
, so that this rule automatically triggers
+on any subtype (e.g. java.io.FileInputStream
). Additionally specifying java.sql.Connection
helps in detecting
+the types, if the type resolution / auxclasspath is not correctly setup.
Note: Since PMD 6.16.0 the default value for the property types
contains java.lang.AutoCloseable
and detects
+now cases where the standard java.io.*Stream
classes are involved. In order to restore the old behaviour,
+just remove "AutoCloseable" from the types.
public class Bar {
+ public void withSQL() {
+ Connection c = pool.getConnection();
+ try {
+ // do stuff
+ } catch (SQLException ex) {
+ // handle exception
+ } finally {
+ // oops, should close the connection using 'close'!
+ // c.close();
+ }
+ }
+
+ public void withFile() {
+ InputStream file = new FileInputStream(new File("/tmp/foo"));
+ try {
+ int c = file.in();
+ } catch (IOException e) {
+ // handle exception
+ } finally {
+ // TODO: close file
+ }
+ }
+ }
+Alternative rule: java:S2095
+]]>{0}
'{1}
' has a cognitive complexity of {2}
, current threshold is {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.
+ public class Foo {
+ // Has a cognitive complexity of 0
+ public void createAccount() {
+ Account account = new Account("PMD");
+ // save account
+ }
+
+ // Has a cognitive complexity of 1
+ public Boolean setPhoneNumberIfNotExisting(Account a, String phone) {
+ if (a.phone == null) { // +1
+ a.phone = phone;
+ return true;
+ }
+
+ return false;
+ }
+
+ // Has a cognitive complexity of 4
+ public void updateContacts(List<Contact> contacts) {
+ List<Contact> contactsToUpdate = new ArrayList<Contact>();
+
+ for (Contact contact : contacts) { // +1
+ if (contact.department.equals("Finance")) { // +2 (nesting = 1)
+ contact.title = "Finance Specialist";
+ contactsToUpdate.add(contact);
+ } else if (contact.department.equals("Sales")) { // +1
+ contact.title = "Sales Specialist";
+ contactsToUpdate.add(contact);
+ }
+ }
+ // save contacts
+ }
+ }
+]]>Reports nested 'if' statements that can be merged together by joining their
+conditions with a boolean &&
operator in between.
class Foo {
+
+ void bar() {
+ if (x) { // original implementation
+ if (y) {
+ // do stuff
+ }
+ }
+ }
+
+ void bar() {
+ if (x && y) { // clearer implementation
+ // do stuff
+ }
+ }
+ }
+Alternative rule: java:S1066
+]]>A rule for the politically correct... we don't want to offend anyone.
+ //OMG, this is horrible, Bob is an idiot !!!
+]]>{0}
'{1}
'
+To avoid mistakes if we want that an Annotation, Class, Enum, Method, Constructor or Field have a default access modifier
+we must add a comment at the beginning of its declaration.
+By default, the comment must be / default /
or / package /
, if you want another, you have to provide a regular expression.
This rule ignores by default all cases that have a @VisibleForTesting
annotation or any JUnit5/TestNG annotation. Use the
+property "ignoredAnnotations" to customize the recognized annotations.
public class Foo {
+ final String stringValue = "some string";
+ String getString() {
+ return stringValue;
+ }
+
+ class NestedFoo {
+ }
+ }
+
+ // should be
+ public class Foo {
+ /* default */ final String stringValue = "some string";
+ /* default */ String getString() {
+ return stringValue;
+ }
+
+ /* default */ class NestedFoo {
+ }
+ }
+]]>Denotes whether javadoc (formal) comments are required (or unwanted) for specific language elements.
+ /**
+ *
+ *
+ * @author Jon Doe
+ */
+]]>Determines whether the dimensions of non-header comments found are within the specified limits.
+ /**
+ *
+ * too many lines!
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ *
+ */
+]]>Use equals()
to compare object references; avoid comparing them with ==
.
Since comparing objects with named constants is useful in some cases (eg, when
+defining constants for sentinel values), the rule ignores comparisons against
+fields with all-caps name (eg this == SENTINEL
), which is a common naming
+convention for constant fields.
You may allow some types to be compared by reference by listing the exceptions
+in the typesThatCompareByReference
property.
class Foo {
+ boolean bar(String a, String b) {
+ return a == b;
+ }
+ }
+Alternative rule: java:S1698
+]]>Reports comparisons with double and float NaN
(Not-a-Number) values.
+ These are specified
+ to have unintuitive behavior: NaN is considered unequal to itself.
+ This means a check like someDouble == Double.NaN
will always return
+ false, even if someDouble
is really the NaN value. To test whether a
+ value is the NaN value, one should instead use Double.isNaN(someDouble)
+ (or Float.isNaN
). The !=
operator should be treated similarly.
+ Finally, comparisons like someDouble <= Double.NaN
are nonsensical
+ and will always evaluate to false.
This rule has been renamed from "BadComparison" in PMD 6.36.0.
+ boolean x = (y == Double.NaN);
+]]>{0}
or {0}
[], or pass varargs parameters separately to clarify intent.
+Reports a confusing argument passed to a varargs method.
+This can occur when an array is passed as a single varargs argument, when the array type is not exactly the + type of array that the varargs method expects. If, that array is a subtype of the component type of the expected + array type, then it might not be clear what value the called varargs method will receive. + For instance if you have: +
void varargs(Object... parm);
+ and call it like so:
+ varargs(new String[]{"a"});
+ it is not clear whether you intended the method to receive the value new Object[]{ new String[] {"a"} }
or
+ just new String[] {"a"}
(the latter happens). This confusion occurs because String[]
is both a subtype
+ of Object[]
and of Object
. To clarify your intent in this case, use a cast or pass individual elements like so:
+ // varargs call
+ // parm will be `new Object[] { "a" }`
+ varargs("a");
+
+ // non-varargs call
+ // parm will be `new String[] { "a" }`
+ varargs((Object[]) new String[]{"a"});
+
+ // varargs call
+ // parm will be `new Object[] { new String[] { "a" } }`
+ varargs((Object) new String[]{"a"});
+Another confusing case is when you pass null
as the varargs argument. Here it is not clear whether you intended
+ to pass an array with a single null element, or a null array (the latter happens). This can similarly be clarified
+ with a cast.
import java.util.Arrays;
+
+ abstract class C {
+ abstract void varargs(Object... args);
+ static {
+ varargs(new String[] { "a" });
+ varargs(null);
+ }
+ }
+]]>Avoid negation within an "if" expression with an "else" clause. For example, rephrase:
+if (x != y) diff(); else same();
as: if (x == y) same(); else diff();
.
Most "if (x != y)" cases without an "else" are often return cases, so consistent use of this +rule makes the code easier to read. Also, this resolves trivial ordering problems, such +as "does the error case go first?" or "does the common case go first?".
+ boolean bar(int x, int y) {
+ return (x != y) ? diff : same;
+ }
+]]>Consecutive calls to StringBuffer/StringBuilder .append should be chained, reusing the target object. This can improve the performance +by producing a smaller bytecode, reducing overhead and improving inlining. A complete analysis can be found here
+ String foo = " ";
+
+ StringBuffer buf = new StringBuffer();
+ buf.append("Hello"); // poor
+ buf.append(foo);
+ buf.append("World");
+
+ StringBuffer buf = new StringBuffer();
+ buf.append("Hello").append(foo).append("World"); // good
+]]>{0}
consecutive times with literals. Use a single append with a single combined String.
+Consecutively calling StringBuffer/StringBuilder.append(...) with literals should be avoided. +Since the literals are constants, they can already be combined into a single String literal and this String +can be appended in a single method call.
+ StringBuilder buf = new StringBuilder();
+ buf.append("Hello").append(" ").append("World"); // poor
+ buf.append("Hello World"); // good
+
+ buf.append('h').append('e').append('l').append('l').append('o'); // poor
+ buf.append("hello"); // good
+
+ buf.append(1).append('m'); // poor
+ buf.append("1m"); // good
+]]>Using constants in interfaces is a bad practice. Interfaces define types, constants are implementation details better placed in classes or enums. If the constants are best viewed as members of an enumerated type, you should export them with an enum type. +For other scenarios, consider using a utility class. See Effective Java's 'Use interfaces only to define types'.
+ public interface ConstantInterface {
+ public static final int CONST1 = 1; // violation, no fields allowed in interface!
+ static final int CONST2 = 1; // violation, no fields allowed in interface!
+ final int CONST3 = 1; // violation, no fields allowed in interface!
+ int CONST4 = 1; // violation, no fields allowed in interface!
+ }
+
+ // with ignoreIfHasMethods = false
+ public interface AnotherConstantInterface {
+ public static final int CONST1 = 1; // violation, no fields allowed in interface!
+
+ int anyMethod();
+ }
+
+ // with ignoreIfHasMethods = true
+ public interface YetAnotherConstantInterface {
+ public static final int CONST1 = 1; // no violation
+
+ int anyMethod();
+ }
+]]>{0}
called during object construction{1}
+Reports calls to overridable methods on this
during object initialization. These
+are invoked on an incompletely constructed object and can be difficult to debug if overridden.
+This is because the subclass usually assumes that the superclass is completely initialized
+in all methods. If that is not the case, bugs can appear in the constructor, for instance,
+some fields that are still null may cause a NullPointerException or be stored somewhere
+else to blow up later.
To avoid this problem, only use methods that are static, private, or final in constructors. +Note that those methods also must not call overridable methods transitively to be safe.
+ public class SeniorClass {
+ public SeniorClass(){
+ toString(); //may throw NullPointerException if overridden
+ }
+ public String toString(){
+ return "IAmSeniorClass";
+ }
+ }
+ public class JuniorClass extends SeniorClass {
+ private String name;
+ public JuniorClass(){
+ super(); //Automatic call leads to NullPointerException
+ name = "JuniorClass";
+ }
+ public String toString(){
+ return name.toUpperCase();
+ }
+ }
+Alternative rule: java:S1699
+]]>Enforce a policy for braces on control statements. It is recommended to use braces on 'if ... else' + statements and loop statements, even if they are optional. This usually makes the code clearer, and + helps prepare the future when you need to add another statement. That said, this rule lets you control + which statements are required to have braces via properties.
+From 6.2.0 on, this rule supersedes WhileLoopMustUseBraces, ForLoopMustUseBraces, IfStmtMustUseBraces, + and IfElseStmtMustUseBraces.
+ while (true) // not recommended
+ x++;
+
+ while (true) { // preferred approach
+ x++;
+ }
+]]>{0}
may denote a high amount of coupling within the class (threshold: {1}
)
+This rule counts the number of unique attributes, local variables, and return types within an object. +A number higher than the specified threshold can indicate a high degree of coupling.
+ import com.Blah;
+ import org.Bar;
+ import org.Bardo;
+
+ public class Foo {
+ private Blah var1;
+ private Bar var2;
+
+ //followed by many imports of unique objects
+ ObjectC doWork() {
+ Bardo var55;
+ ObjectA var44;
+ ObjectZ var93;
+ return something();
+ }
+ }
+Alternative rule: java:S1200
+]]>{0}
'{1}
' has a{2}
cyclomatic complexity of {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
. For more
+details on the calculation, see the documentation CYCLO
.
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 80, 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.
+ 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;
+ }
+ }
+ }
+ }
+Alternative rule: java:S1541
+]]>{0}
' is suspected to be a Data Class (WOC={1}
, NOPA={2}
, NOAM={3}
, WMC={4}
)
+Data Classes are simple data holders, which reveal most of their state, and +without complex functionality. The lack of functionality may indicate that +their behaviour is defined elsewhere, which is a sign of poor data-behaviour +proximity. By directly exposing their internals, Data Classes break encapsulation, +and therefore reduce the system's maintainability and understandability. Moreover, +classes tend to strongly rely on their data representation, which makes for a brittle +design.
+Refactoring a Data Class should focus on restoring a good data-behaviour proximity. In +most cases, that means moving the operations defined on the data back into the class. +In some other cases it may make sense to remove entirely the class and move the data +into the former client classes.
+The rule uses metrics to implement its detection strategy. The violation message gives information about the values of these metrics:
+WEIGHED_METHOD_COUNT
WEIGHT_OF_CLASS
NUMBER_OF_PUBLIC_FIELDS
NUMBER_OF_ACCESSORS
The rule identifies a god class by looking for classes which have all of the following properties:
+ public class DataClass {
+
+ // class exposes public attributes
+ public String name = "";
+ public int bar = 0;
+ public int na = 0;
+
+ private int bee = 0;
+
+ // and private ones through getters
+ public void setBee(int n) {
+ bee = n;
+ }
+ }
+]]>By convention, the default label should be the last label in a switch statement or switch expression.
+Note: This rule has been renamed from "DefaultLabelNotLastInSwitchStmt" with PMD 7.7.0.
+ public class Foo {
+ void bar(int a) {
+ switch (a) {
+ case 1: // do something
+ break;
+ default: // the default case should be last, by convention
+ break;
+ case 2:
+ break;
+ }
+ }
+ }
+]]>The method appears to be a test case since it has public or default visibility, +non-static access, no arguments, no return value, has no annotations, but is a +member of a class that has one or more JUnit test cases. If it is a utility +method, it should likely have private visibility. If it is an ignored test, it +should be annotated with @Test and @Ignore.
+ public class MyTest {
+ @Test
+ public void someTest() {
+ }
+
+ // violation: Not annotated
+ public void someOtherTest () {
+ }
+
+ }
+]]>Calls to System.gc()
, Runtime.getRuntime().gc()
, and System.runFinalization()
are not advised.
+Code should have the same behavior whether the garbage collection is disabled using the option
+-Xdisableexplicitgc
or not.
Moreover, "modern" JVMs do a very good job handling garbage collections. If memory usage issues unrelated to memory +leaks develop within an application, it should be dealt with JVM options rather than within the code itself.
+ public class GCCall {
+ public GCCall() {
+ // Explicit gc call !
+ System.gc();
+ }
+
+ public void doSomething() {
+ // Explicit gc call !
+ Runtime.getRuntime().gc();
+ }
+
+ public explicitGCcall() {
+ // Explicit gc call !
+ System.gc();
+ }
+
+ public void doSomething() {
+ // Explicit gc call !
+ Runtime.getRuntime().gc();
+ }
+ }
+Alternative rule: java:S1215
+]]>Errors are system exceptions. Do not extend them.
+ public class Foo extends Error { }
+Alternative rule: java:S1194
+]]>Extend Exception or RuntimeException instead of Throwable.
+ public class Foo extends Throwable { }
+]]>Use Environment.getExternalStorageDirectory() instead of "/sdcard"
+ public class MyActivity extends Activity {
+ protected void foo() {
+ String storageLocation = "/sdcard/mypackage"; // hard-coded, poor approach
+
+ storageLocation = Environment.getExternalStorageDirectory() + "/mypackage"; // preferred approach
+ }
+ }
+]]>Web applications should not call System.exit()
, since only the web container or the
+application server should stop the JVM. Otherwise a web application would terminate all other applications
+running on the same application server.
This rule also checks for the equivalent calls Runtime.getRuntime().exit()
and Runtime.getRuntime().halt()
.
This rule has been renamed from "DoNotCallSystemExit" in PMD 6.29.0.
+ public void bar() {
+ System.exit(0); // never call this when running in an application server!
+ }
+ public void foo() {
+ Runtime.getRuntime().exit(0); // never stop the JVM manually, the container will do this.
+ }
+]]>Throwing exceptions within a 'finally' block is confusing since they may mask other exceptions +or code defects. +
Note: This is a PMD implementation of the Lint4j rule "A throw in a finally block"
+ public class Foo {
+ public void bar() {
+ try {
+ // Here do some stuff
+ } catch( Exception e) {
+ // Handling the issue
+ } finally {
+ // is this really a good idea ?
+ throw new Exception();
+ }
+ }
+ }
+Alternative rule: java:S1163
+]]>The J2EE specification explicitly forbids the use of threads. Threads are resources, that should be managed and monitored by the J2EE server. +If the application creates threads on its own or uses own custom thread pools, then these threads are not managed, which could lead to resource exhaustion. +Also, EJBs might be moved between machines in a cluster and only managed resources can be moved along.
+ // This is not allowed
+ public class UsingThread extends Thread {
+
+ }
+
+ // Neither this,
+ public class UsingExecutorService {
+
+ public void methodX() {
+ ExecutorService executorService = Executors.newFixedThreadPool(5);
+ }
+ }
+
+ // Nor this,
+ public class Example implements ExecutorService {
+
+ }
+
+ // Nor this,
+ public class Example extends AbstractExecutorService {
+
+ }
+
+ // Nor this
+ public class UsingExecutors {
+
+ public void methodX() {
+ Executors.newSingleThreadExecutor().submit(() -> System.out.println("Hello!"));
+ }
+ }
+]]>Explicitly calling Thread.run() method will execute in the caller's thread of control. Instead, call Thread.start() for the intended behavior.
+ Thread t = new Thread();
+ t.run(); // use t.start() instead
+ new Thread().run(); // same violation
+Alternative rule: java:S1217
+]]>Avoid importing anything from the 'sun.*' packages. These packages are not portable +and are likely to change.
+If you find yourself having to depend on Sun APIs, confine this dependency to as +small a scope as possible, for instance by writing a stable wrapper class around +the unstable API. You can then suppress this rule in the implementation of the wrapper.
+ import sun.misc.foo;
+ public class Foo {}
+Alternative rule: java:S1191
+]]>Don't use floating point for loop indices. If you must use floating point, use double +unless you're certain that float provides enough precision and you have a compelling +performance need (space or time).
+ public class Count {
+ public static void main(String[] args) {
+ final int START = 2000000000;
+ int count = 0;
+ for (float f = START; f < START + 50; f++)
+ count++;
+ //Prints 0 because (float) START == (float) (START + 50).
+ System.out.println(count);
+ //The termination test misbehaves due to floating point granularity.
+ }
+ }
+]]>Double brace initialisation is a pattern to initialise eg collections concisely. But it implicitly + generates a new .class file, and the object holds a strong reference to the enclosing object. For those + reasons, it is preferable to initialize the object normally, even though it's verbose.
+This rule counts any anonymous class which only has a single initializer as an instance of double-brace + initialization. There is currently no way to find out whether a method called in the initializer is not + accessible from outside the anonymous class, and those legit cases should be suppressed for the time being.
+ // this is double-brace initialization
+ return new ArrayList<String>(){{
+ add("a");
+ add("b");
+ add("c");
+ }};
+
+ // the better way is to not create an anonymous class:
+ List<String> a = new ArrayList<>();
+ a.add("a");
+ a.add("b");
+ a.add("c");
+ return a;
+]]>Partially created objects can be returned by the Double Checked Locking pattern when used in Java. +An optimizing JRE may assign a reference to the baz variable before it calls the constructor of the object the +reference points to.
+Note: With Java 5, you can make Double checked locking work, if you declare the variable to be volatile
.
For more details refer to: http://www.javaworld.com/javaworld/jw-02-2001/jw-0209-double.html +or http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html
+ public class Foo {
+ /*volatile */ Object baz = null; // fix for Java5 and later: volatile
+ Object bar() {
+ if (baz == null) { // baz may be non-null yet not fully created
+ synchronized(this) {
+ if (baz == null) {
+ baz = new Object();
+ }
+ }
+ }
+ return baz;
+ }
+ }
+]]>Empty Catch Block finds instances where an exception is caught, but nothing is done. +In most circumstances, this swallows an exception which should either be acted on +or reported.
+ public void doSomething() {
+ try {
+ FileInputStream fis = new FileInputStream("/tmp/bugger");
+ } catch (IOException ioe) {
+ // not good
+ }
+ }
+Alternative rule: java:S108
+]]>Reports control statements whose body is empty, as well as empty initializers.
+The checked code constructs are the following:
+try
statementsfinally
clauses of try
statementsswitch
statementssynchronized
statementsif
statementswhile
, for
, do .. while
This rule replaces the rules EmptyFinallyBlock, + EmptyIfStmt, EmptyInitializer, EmptyStatementBlock, + EmptySwitchStatements, EmptySynchronizedBlock, EmptyTryBlock, and EmptyWhileStmt.
+Notice that {% rule java/errorprone/EmptyCatchBlock %} is still an independent rule.
+EmptyStatementNotInLoop is replaced by {% rule java/codestyle/UnnecessarySemicolon %}.
+ class Foo {
+ {
+ if (true); // empty if statement
+ if (true) { // empty as well
+ }
+ }
+
+ {} // empty initializer
+ }
+]]>Empty finalize methods serve no purpose and should be removed. Note that Oracle has declared Object.finalize() as deprecated since JDK 9.
+ public class Foo {
+ protected void finalize() {}
+ }
+Alternative rule: java:S1186
+]]>Empty or auto-generated methods in an abstract class should be tagged as abstract. This helps to remove their inapproprate +usage by developers who should be implementing their own versions in the concrete subclasses.
+ public abstract class ShouldBeAbstract {
+ public Object couldBeAbstract() {
+ // Should be abstract method ?
+ return null;
+ }
+
+ public void couldBeAbstract() {
+ }
+ }
+]]>Tests for null should not use the equals() method. The '==' operator should be used instead.
+ String x = "foo";
+
+ if (x.equals(null)) { // bad form
+ doSomething();
+ }
+
+ if (x == null) { // preferred
+ doSomething();
+ }
+Alternative rule: java:S2159
+]]>{0}
is caught in this block.
+This rule reports exceptions thrown and caught in an enclosing try statement.
+This use of exceptions as a form of goto
statement is discouraged, as that may
+hide actual exceptions, and obscures control flow, especially when debugging.
+To fix a violation, add the necessary validation or use an alternate control structure.
public void bar() {
+ try {
+ try {
+ } catch (Exception e) {
+ throw new WrapperException(e);
+ // this is essentially a GOTO to the WrapperException catch block
+ }
+ } catch (WrapperException e) {
+ // do some more stuff
+ }
+ }
+Alternative rule: java:S1141
+]]>A high number of imports can indicate a high degree of coupling within an object. This rule +counts the number of unique imports and reports a violation if the count is above the +user-specified threshold.
+ import blah.blah.Baz;
+ import blah.blah.Bif;
+ // 28 others from the same package elided
+ public class Foo {
+ public void doWork() {}
+ }
+Alternative rule: java:S1200
+]]>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.
+ public void addPerson( // too many arguments liable to be mixed up
+ int birthYear, int birthMonth, int birthDate, int height, int weight, int ssn) {
+
+ . . . .
+ }
+
+ public void addPerson( // preferred approach
+ Date birthdate, BodyMeasurements measurements, int ssn) {
+
+ . . . .
+ }
+Alternative rule: java:S107
+]]>Classes with large numbers of public methods and attributes require disproportionate testing efforts +since combinational 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.
+ 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 ...]
+ }
+Alternative rule: java:S1448
+]]>When switching over an enum or sealed class, the compiler will ensure that all possible cases are covered. +If a case is missing, this will result in a compilation error. But if a default case is added, this compiler +check is not performed anymore, leading to difficulties in noticing bugs at runtime.
+Not using a default case makes sure, a compiler error is introduced whenever a new enum constant or a +new subclass to the sealed class hierarchy is added. We will discover this problem at compile time +rather than at runtime (if at all).
+Note: The fix it not necessarily just removing the default case. Maybe a case is missing which needs to be implemented.
+ class Foo {
+ enum MyEnum { A, B };
+
+ void doSomething(MyEnum e) {
+ switch(e) {
+ case A -> System.out.println("a");
+ case B -> System.out.println("b");
+ default -> System.out.println("unnecessary default");
+ };
+ }
+ }
+]]>No need to explicitly extend Object.
+ public class Foo extends Object { // not required
+ }
+Alternative rule: java:S1939
+]]>Fields should be declared at the top of the class, before any method declarations, constructors, initializers or inner classes.
+ public class HelloWorldBean {
+
+ // Field declared before methods / inner classes - OK
+ private String _thing;
+
+ public String getMessage() {
+ return "Hello World!";
+ }
+
+ // Field declared after methods / inner classes - avoid this
+ private String _fieldInWrongLocation;
+ }
+Alternative rule: java:S1213
+]]>{0}
name '{1}
' doesn't match '{2}
'
+Configurable naming conventions for field declarations. This rule reports variable declarations + which do not match the regex that applies to their specific kind ---e.g. constants (static final), + enum constant, final field. Each regex can be configured through properties.
+By default this rule uses the standard Java naming convention (Camel case), and uses the ALL_UPPER + convention for constants and enum constants.
+ class Foo {
+ int myField = 1; // This is in camel case, so it's ok
+ int my_Field = 1; // This contains an underscore, it's not ok by default
+ // but you may allow it, or even require the "my_" prefix
+
+ final int FinalField = 1; // you may configure a different convention for final fields,
+ // e.g. here PascalCase: [A-Z][a-zA-Z0-9]*
+
+ interface Interface {
+ double PI = 3.14; // interface "fields" use the constantPattern property
+ }
+
+ enum AnEnum {
+ ORG, NET, COM; // These use a separate property but are set to ALL_UPPER by default
+ }
+ }
+]]>If a final field is assigned to a compile-time constant, it could be made static, thus saving overhead +in each object at runtime.
+ public class Foo {
+ public final int BAR = 42; // this could be static and save some space
+ }
+Alternative rule: java:S1170
+]]>Declaring a method parameter as final for an interface method is useless because the implementation may choose to not respect it.
+ public interface MyInterface {
+ void process(final Object arg); // Avoid using final here
+ }
+]]>If the finalize() is implemented, its last action should be to call super.finalize. Note that Oracle has declared Object.finalize() as deprecated since JDK 9.
+ protected void finalize() {
+ something();
+ // neglected to call super.finalize()
+ }
+]]>If the finalize() is implemented, it should do something besides just calling super.finalize(). Note that Oracle has declared Object.finalize() as deprecated since JDK 9.
+ protected void finalize() {
+ super.finalize();
+ }
+Alternative rule: java:S1185
+]]>Methods named finalize() should not have parameters. It is confusing and most likely an attempt to +overload Object.finalize(). It will not be called by the VM.
+Note that Oracle has declared Object.finalize() as deprecated since JDK 9.
+ public class Foo {
+ // this is confusing and probably a bug
+ protected void finalize(int a) {
+ }
+ }
+Alternative rule: java:S1175
+]]>When overriding the finalize(), the new method should be set as protected. If made public, +other classes may invoke it at inappropriate times.
+Note that Oracle has declared Object.finalize() as deprecated since JDK 9.
+ public void finalize() {
+ // do something
+ }
+Alternative rule: java:S1174
+]]>Reports loops that can be safely replaced with the foreach syntax. The rule considers loops over +lists, arrays and iterators. A loop is safe to replace if it only uses the index variable to +access an element of the list or array, only has one update statement, and loops through every +element of the list or array left to right.
+ public class MyClass {
+ void loop(List<String> l) {
+ for (int i = 0; i < l.size(); i++) { // pre Java 1.5
+ System.out.println(l.get(i));
+ }
+
+ for (String s : l) { // post Java 1.5
+ System.out.println(s);
+ }
+ }
+ }
+]]>Some for loops can be simplified to while loops, this makes them more concise.
+ public class Foo {
+ void bar() {
+ for (;true;) true; // No Init or Update part, may as well be: while (true)
+ }
+ }
+Alternative rule: java:S1264
+]]>Having a lot of control variables in a 'for' loop makes it harder to see what range of values +the loop iterates over. By default this rule allows a regular 'for' loop with only one variable.
+ // this will be reported with the default setting of at most one control variable in a for loop
+ for (int i = 0, j = 0; i < 10; i++, j += 2) {
+ foo();
+]]>{0}
name '{1}
' doesn't match '{2}
'
+Configurable naming conventions for formal parameters of methods and lambdas. + This rule reports formal parameters which do not match the regex that applies to their + specific kind (e.g. lambda parameter, or final formal parameter). Each regex can be + configured through properties.
+By default this rule uses the standard Java naming convention (Camel case).
+ class Foo {
+
+ abstract void bar(int myInt); // This is Camel case, so it's ok
+
+ void bar(int my_i) { // this will be reported
+
+ }
+
+ void lambdas() {
+
+ // lambdas parameters can be configured separately
+ Consumer<String> lambda1 = s_str -> { };
+
+ // lambda parameters with an explicit type can be configured separately
+ Consumer<String> lambda1 = (String str) -> { };
+
+ }
+
+ }
+]]>Names for references to generic values should be limited to a single uppercase letter.
+ public interface GenericDao<E extends BaseModel, K extends Serializable> extends BaseDao {
+ // This is ok...
+ }
+
+ public interface GenericDao<E extends BaseModel, K extends Serializable> {
+ // Also this
+ }
+
+ public interface GenericDao<e extends BaseModel, K extends Serializable> {
+ // 'e' should be an 'E'
+ }
+
+ public interface GenericDao<EF extends BaseModel, K extends Serializable> {
+ // 'EF' is not ok.
+ }
+Alternative rule: java:S119
+]]>{0}
, ATFD={2}
, TCC={1}
)
+The God Class rule detects the God Class design flaw using metrics. God classes do too many things, +are very big and overly complex. They should be split apart to be more object-oriented. +The rule uses the detection strategy described in "Object-Oriented Metrics in Practice". +The violations are reported against the entire class.
+The rule uses metrics to implement its detection strategy. The violation message gives information about the values of these metrics:
+WEIGHED_METHOD_COUNT
ACCESS_TO_FOREIGN_DATA
TIGHT_CLASS_COHESION
The rule identifies a god class by looking for classes which have all of the following properties:
+See also the reference:
+Michele Lanza and Radu Marinescu. Object-Oriented Metrics in Practice: +Using Software Metrics to Characterize, Evaluate, and Improve the Design +of Object-Oriented Systems. Springer, Berlin, 1 edition, October 2006. Page 80.
+]]>Whenever using a log level, one should check if it is actually enabled, or +otherwise skip the associate String creation and manipulation, as well as any method calls.
+An alternative to checking the log level are substituting parameters, formatters or lazy logging +with lambdas. The available alternatives depend on the actual logging framework.
+ // Add this for performance - avoid manipulating strings if the logger may drop it
+ if (log.isDebugEnabled()) {
+ log.debug("log something" + param1 + " and " + param2 + "concat strings");
+ }
+
+ // Avoid the guarding if statement with substituting parameters
+ log.debug("log something {} and {}", param1, param2);
+
+ // Avoid the guarding if statement with formatters
+ log.debug("log something %s and %s", param1, param2);
+
+ // This is still an issue, method invocations may be expensive / have side-effects
+ log.debug("log something expensive: {}", calculateExpensiveLoggingText());
+
+ // Avoid the guarding if statement with lazy logging and lambdas
+ log.debug("log something expensive: {}", () -> calculateExpensiveLoggingText());
+
+ // … alternatively use method references
+ log.debug("log something expensive: {}", this::calculateExpensiveLoggingText);
+]]>Do not use hard coded values for cryptographic operations. Please store keys outside of source code.
+ public class Foo {
+ void good() {
+ SecretKeySpec secretKeySpec = new SecretKeySpec(Properties.getKey(), "AES");
+ }
+
+ void bad() {
+ SecretKeySpec secretKeySpec = new SecretKeySpec("my secret here".getBytes(), "AES");
+ }
+ }
+]]>Avoid idempotent operations - they have no effect.
+ public class Foo {
+ public void bar() {
+ int x = 2;
+ x = x;
+ }
+ }
+Alternative rule: java:S1656
+]]>{0}
' branch
+Identical catch
branches use up vertical space and increase the complexity of code without
+ adding functionality. It's better style to collapse identical branches into a single multi-catch
+ branch.
try {
+ // do something
+ } catch (IllegalArgumentException e) {
+ throw e;
+ } catch (IllegalStateException e) { // Can be collapsed into the previous block
+ throw e;
+ }
+
+ try {
+ // do something
+ } catch (IllegalArgumentException | IllegalStateException e) { // This is better
+ throw e;
+ }
+]]>{0}
' may be declared final
+Reports non-final fields whose value never changes once object initialization ends, +and hence may be marked final.
+Note that this rule does not enforce that the field value be deeply immutable itself. +An object can still have mutable state, even if all its member fields are declared final. +This is referred to as shallow immutability. For more information on mutability, +see Effective Java, 3rd Edition, Item 17: Minimize mutability.
+Limitations: We can only check private fields for now.
+ public class Foo {
+ private int x; // could be final
+ public Foo() {
+ x = 7;
+ }
+ public void foo() {
+ int a = x + 2;
+ }
+ }
+]]>Reports functional interfaces that were not explicitly declared as such with
+ the annotation @FunctionalInterface
. If an interface is accidentally a functional
+ interface, then it should bear a @SuppressWarnings("PMD.ImplicitFunctionalInterface")
+ annotation to make this clear.
// The intent on this declaration is unclear, and the rule will report it.
+ public interface MyInterface {
+ void doSomething();
+ }
+
+ // This is clearly intended as a functional interface.
+ @FunctionalInterface
+ public interface MyInterface {
+ void doSomething();
+ }
+
+ // This is clearly NOT intended as a functional interface.
+ @SuppressWarnings("PMD.ImplicitFunctionalInterface")
+ public interface MyInterface {
+ void doSomething();
+ }
+]]>Switch statements without break or return statements for each case option +may indicate problematic behaviour. Empty cases are ignored as these indicate +an intentional fall-through.
+You can ignore a violation by commenting // fallthrough
before the case label
+which is reached by fallthrough, or with @SuppressWarnings("fallthrough")
.
This rule has been renamed from "MissingBreakInSwitch" in PMD 6.37.0.
+ public void bar(int status) {
+ switch(status) {
+ case CANCELLED:
+ doCancelled();
+ // break; hm, should this be commented out?
+ case NEW:
+ doNew();
+ // is this really a fall-through?
+ // what happens if you add another case after this one?
+ case REMOVED:
+ doRemoved();
+ // fallthrough - this comment just clarifies that you want a fallthrough
+ case OTHER: // empty case - this is interpreted as an intentional fall-through
+ case ERROR:
+ doErrorHandling();
+ break;
+ }
+ }
+]]>String.trim().length() == 0 (or String.trim().isEmpty() for the same reason) is an inefficient +way to check if a String is really blank, as it creates a new String object just to check its size. +Consider creating a static function that loops through a string, checking Character.isWhitespace() +on each character and returning false if a non-whitespace character is found. A Smarter code to +check for an empty string would be:
+ private boolean checkTrimEmpty(String str) {
+ for(int i = 0; i < str.length(); i++) {
+ if(!Character.isWhitespace(str.charAt(i))) {
+ return false;
+ }
+ }
+ return true;
+ }
+You can refer to Apache's StringUtils#isBlank (in commons-lang), +Spring's StringUtils#hasText (in the Spring framework) or Google's +CharMatcher#whitespace (in Guava) for existing implementations (some might +include the check for != null).
+ public void bar(String string) {
+ if (string != null && string.trim().length() > 0) {
+ doSomething();
+ }
+ }
+]]>Avoid concatenating non-literals in a StringBuffer constructor or append() since intermediate buffers will +need to be be created and destroyed by the JVM.
+ // Avoid this, two buffers are actually being created here
+ StringBuffer sb = new StringBuffer("tmp = "+System.getProperty("java.io.tmpdir"));
+
+ // do this instead
+ StringBuffer sb = new StringBuffer("tmp = ");
+ sb.append(System.getProperty("java.io.tmpdir"));
+]]>Do not use hard coded initialization vector in cryptographic operations. Please use a randomly generated IV.
+ public class Foo {
+ void good() {
+ SecureRandom random = new SecureRandom();
+ byte iv[] = new byte[16];
+ random.nextBytes(bytes);
+ }
+
+ void bad() {
+ byte[] iv = new byte[] { 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, };
+ }
+
+ void alsoBad() {
+ byte[] iv = "secret iv in here".getBytes();
+ }
+ }
+]]>Avoid instantiating an object just to call getClass() on it; use the .class public member instead.
+ // replace this
+ Class c = new String().getClass();
+
+ // with this:
+ Class c = String.class;
+Alternative rule: java:S2133
+]]>{0}
has been initialized with size {1}
, but has at least {2}
characters appended.
+Failing to pre-size a StringBuffer or StringBuilder properly could cause it to re-size many times +during runtime. This rule attempts to determine the total number the characters that are actually +passed into StringBuffer.append(), but represents a best guess "worst case" scenario. An empty +StringBuffer/StringBuilder constructor initializes the object to 16 characters. This default +is assumed if the length of the constructor can not be determined.
+ StringBuilder bad = new StringBuilder();
+ bad.append("This is a long string that will exceed the default 16 characters");
+
+ StringBuilder good = new StringBuilder(41);
+ good.append("This is a long string, which is pre-sized");
+]]>{0}
' is missing a getter for property '{1}
'.
+Identifies beans, that don't follow the JavaBeans API specification.
+Each non-static field should have both a getter and a setter method. If the field is just used internally and is not
+a bean property, then the field should be marked as transient
.
The rule verifies that the type of the field is the same as the result type of the getter. And that this type matches +the type used in the setter.
+The rule also checks, that there is a no-arg or default constructor available.
+Optionally the rule also verifies, that the bean implements java.io.Serializable
. While this is a requirement for the
+original JavaBeans specification, frameworks nowadays don't strictly require this anymore.
In order to avoid many false positives in classes that are not beans, the rule needs to be explicitly
+enabled by configuring the property packages
.
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;
+ }
+ }
+]]>Check for messages in slf4j and log4j2 (since 6.19.0) loggers with non matching number of arguments and placeholders.
+Since 6.32.0 in addition to parameterized message placeholders ({}
) also format specifiers of string formatted
+messages are supported (%s
).
This rule has been renamed from "InvalidSlf4jMessageFormat" in PMD 6.19.0.
+ LOGGER.error("forget the arg {}");
+ LOGGER.error("forget the arg %s");
+ LOGGER.error("too many args {}", "arg1", "arg2");
+ LOGGER.error("param {}", "arg1", new IllegalStateException("arg")); //The exception is shown separately, so is correct.
+]]>In JUnit 3, test suites are indicated by the suite() method. In JUnit 4, suites are indicated +through the @RunWith(Suite.class) annotation.
+ public class BadExample extends TestCase{
+
+ public static Test suite(){
+ return new Suite();
+ }
+ }
+
+ @RunWith(Suite.class)
+ @SuiteClasses( { TestOne.class, TestTwo.class })
+ public class GoodTest {
+ }
+]]>Reports JUnit 5 test classes and methods that are not package-private. +Contrary to JUnit 4 tests, which required public visibility to be run by the engine, +JUnit 5 tests can also be run if they're package-private. Marking them as such +is a good practice to limit their visibility.
+Test methods are identified as those which use @Test
, @RepeatedTest
,
+@TestFactory
, @TestTemplate
or @ParameterizedTest
.
class MyTest { // not public, that's fine
+ @Test
+ public void testBad() { } // should not have a public modifier
+
+ @Test
+ protected void testAlsoBad() { } // should not have a protected modifier
+
+ @Test
+ private void testNoRun() { } // should not have a private modifier
+
+ @Test
+ void testGood() { } // package private as expected
+ }
+]]>In JUnit 3, the setUp method is used to set up all data entities required in running tests. + The tearDown method is used to clean up all data entities required in running tests. + You should not misspell method name if you want your test to set up and clean up everything correctly.
+ import junit.framework.*;
+
+ public class Foo extends TestCase {
+ public void setup() {} // oops, should be setUp
+ public void TearDown() {} // oops, should be tearDown
+ }
+]]>The suite() method in a JUnit test needs to be both public and static.
+ import junit.framework.*;
+
+ public class Foo extends TestCase {
+ public void suite() {} // oops, should be static
+ }
+ import junit.framework.*;
+
+ public class Foo extends TestCase {
+ private static void suite() {} // oops, should be public
+ }
+]]>In JUnit4, use the @Test(expected) annotation to denote tests that should throw exceptions.
+ public class MyTest {
+ @Test
+ public void testBad() {
+ try {
+ doSomething();
+ fail("should have thrown an exception");
+ } catch (Exception e) {
+ }
+ }
+
+ @Test(expected=Exception.class)
+ public void testGood() {
+ doSomething();
+ }
+ }
+]]>Avoid jumbled loop incrementers - it's usually a mistake, and is confusing even if intentional.
+ public class JumbledIncrementerRule1 {
+ public void foo() {
+ for (int i = 0; i < 10; i++) { // only references 'i'
+ for (int k = 0; k < 20; i++) { // references both 'i' and 'k'
+ System.out.println("Hello");
+ }
+ }
+ }
+ }
+Alternative rule: java:S1994
+]]><code>{0}</code>
+This rule reports lambda expressions that can be written more succinctly as a method reference. This is the case if the lambda is an expression lambda that only calls one method, passing the entire lambda parameter list in order to the method. For instance: +
x -> Foo.call(x) // can be Foo::call
+ x -> call(x) // can be this::call, if call is an instance method
+ (x, y, z) -> call(x, y, z) // can be this::call
+ () -> foo.get() // can be foo::get
+ x -> x.foo() // can be XType::foo (where XType is the type of x)
+In some cases rewriting a lambda to a method reference can change the semantics of the code. For instance in (x) -> someVar.call(x)
, the invocation of the lambda may produce a NullPointerException (NPE) if someVar
is null. The method reference someVar::call
will also NPE if someVar
is null, but it will do so at the point the method reference is created, while the lambda is created without error and its NPE is only thrown if the lambda is invoked (which may be never). Code should probably not rely on this subtle semantic difference, therefore these potentially problematic lambdas are also reported by default. This behavior can be disabled by setting the property ignoreIfMayNPE
to true
.
The property ignoreIfMayNPE
is true by default. By default, calls whose receiver is itself a method call are ignored, because they could cause side effects. This may be changed by setting the property ignoreIfReceiverIsMethod
to false
.
Scope limitations:
+x -> new CtorCall().something(x)
, because the semantics of the method reference would be to create a single new object, while the lambda creates one object per invocation.(x) -> sideEffectingMethod().foo(x)
will be reported. Suppress the warning in this case. 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();
+ }
+ }
+]]>{0}
)
+The law of Demeter is a simple rule that says "only talk to friends". It forbids +fetching data from "too far away", for some definition of distance, in order to +reduce coupling between classes or objects of different levels of abstraction.
+The rule uses a notion of "degree", that quantifies how "far" an object is. Expressions with too high degree can only be used in certain ways. The degree of an expression is defined inductively:
+this
is 0expr.field
is the degree of expr
plus 1expr.getFoo()
is the degree of expr
plus 1expr.withFoo("")
is the degree of expr
Intuitively, the more you call getters, the more the degree increases. Eventually
+the degree reaches the report threshold (property trustRadius
) and the expression
+is reported. The details of the calculation are more involved and make room for common
+patterns, like usage of collections (objects that are in a list or array have the
+same degree as their container), the builder pattern, and getters that do not appear
+to break a boundary of abstraction.
Be aware that this rule is prone to many false-positives and low-priority warnings. You can increase the trustRadius
property to reduce them drastically. The default trustRadius
of 1 corresponds to the original law of Demeter (you're only allowed one getter call on untrusted values). Given some trustRadius
value:
trustRadius
are not reportedtrustRadius + 1
are reported, unless they are only returned from the current method, or passed as argument to another method. Without this exception ittrustRadius + 1
are not reported. The intuition is that to obtain a value of degree n > 1
then you must use an expressionSee also the references:
+ public class Foo {
+ /**
+ * This example will result in one violation.
+ */
+ public void example(Bar b) { // b has degree 1
+ // `b.getC()` has degree 2, it's breaking a boundary of abstraction and so is reported.
+ b.getC().doIt();
+ // To respect the law of Demeter, Bar should encapsulate its
+ // C member more properly, eg by exposing a method like this:
+ b.callDoItOnC();
+
+ // a constructor call, not a method call.
+ D d = new D();
+ // this method call is ok, because we have create the new
+ // instance of D locally.
+ d.doSomethingElse();
+ }
+ }
+]]>This rule finds Linguistic Naming Antipatterns. It checks for fields, that are named, as if they should + be boolean but have a different type. It also checks for methods, that according to their name, should + return a boolean, but don't. Further, it checks, that getters return something and setters won't. + Finally, it checks that methods, that start with "to" - so called transform methods - actually return + something, since according to their name, they should convert or transform one object into another. + There is additionally an option, to check for methods that contain "To" in their name - which are + also transform methods. However, this is disabled by default, since this detection is prone to + false positives.
+For more information, see Linguistic Antipatterns - What They Are and How +Developers Perceive Them.
+ public class LinguisticNaming {
+ int isValid; // the field name indicates a boolean, but it is an int.
+ boolean isTrue; // correct type of the field
+
+ void myMethod() {
+ int hasMoneyLocal; // the local variable name indicates a boolean, but it is an int.
+ boolean hasSalaryLocal; // correct naming and type
+ }
+
+ // the name of the method indicates, it is a boolean, but the method returns an int.
+ int isValid() {
+ return 1;
+ }
+ // correct naming and return type
+ boolean isSmall() {
+ return true;
+ }
+
+ // the name indicates, this is a setter, but it returns something
+ int setName() {
+ return 1;
+ }
+
+ // the name indicates, this is a getter, but it doesn't return anything
+ void getName() {
+ // nothing to return?
+ }
+
+ // the name indicates, it transforms an object and should return the result
+ void toDataType() {
+ // nothing to return?
+ }
+ // the name indicates, it transforms an object and should return the result
+ void grapeToWine() {
+ // nothing to return?
+ }
+ }
+]]>Position literals first in all String comparisons, if the second argument is null then NullPointerExceptions + can be avoided, they will just return false. Note that switching literal positions for compareTo and + compareToIgnoreCase may change the result, see examples.
+Note that compile-time constant strings are treated like literals. This is because they are inlined into + the class file, are necessarily non-null, and therefore cannot cause an NPE at runtime.
+ class Foo {
+ boolean bar(String x) {
+ return x.equals("2"); // should be "2".equals(x)
+ }
+ boolean bar(String x) {
+ return x.equalsIgnoreCase("2"); // should be "2".equalsIgnoreCase(x)
+ }
+ boolean bar(String x) {
+ return (x.compareTo("bar") > 0); // should be: "bar".compareTo(x) < 0
+ }
+ boolean bar(String x) {
+ return (x.compareToIgnoreCase("bar") > 0); // should be: "bar".compareToIgnoreCase(x) < 0
+ }
+ boolean bar(String x) {
+ return x.contentEquals("bar"); // should be "bar".contentEquals(x)
+ }
+
+ static final String CONSTANT = "const";
+ {
+ CONSTANT.equals("literal"); // not reported, this is effectively the same as writing "const".equals("foo")
+ }
+ }
+]]>The Local Home interface of a Session EJB should be suffixed by 'LocalHome'.
+ public interface MyBeautifulLocalHome extends javax.ejb.EJBLocalHome {} // proper name
+
+ public interface MissingProperSuffix extends javax.ejb.EJBLocalHome {} // non-standard name
+]]>The Local Interface of a Session EJB should be suffixed by 'Local'.
+ public interface MyLocal extends javax.ejb.EJBLocalObject {} // proper name
+
+ public interface MissingProperSuffix extends javax.ejb.EJBLocalObject {} // non-standard name
+]]>{0}
' could be declared final
+A local variable assigned only once can be declared final.
+ public class Bar {
+ public void foo () {
+ String txtA = "a"; // if txtA will not be assigned again it is better to do this:
+ final String txtB = "b";
+ }
+ }
+]]>{0}
name '{1}
' doesn't match '{2}
'
+Configurable naming conventions for local variable declarations and other locally-scoped + variables. This rule reports variable declarations which do not match the regex that applies to their + specific kind (e.g. final variable, or catch-clause parameter). Each regex can be configured through + properties.
+By default this rule uses the standard Java naming convention (Camel case).
+ class Foo {
+ void bar() {
+ int localVariable = 1; // This is in camel case, so it's ok
+ int local_variable = 1; // This will be reported unless you change the regex
+
+ final int i_var = 1; // final local variables can be configured separately
+
+ try {
+ foo();
+ } catch (IllegalArgumentException e_illegal) {
+ // exception block parameters can be configured separately
+ }
+
+ }
+ }
+]]>Use opposite operator instead of negating the whole expression with a logic complement operator.
+ public boolean bar(int a, int b) {
+
+ if (!(a == b)) { // use !=
+ return false;
+ }
+
+ if (!(a < b)) { // use >=
+ return false;
+ }
+
+ return true;
+ }
+Alternative rule: java:S1940
+]]>{0}
+Fields, formal arguments, or local variable names that are too long can make the code difficult to follow.
+ public class Something {
+ int reallyLongIntName = -3; // VIOLATION - Field
+ public static void main( String argumentsList[] ) { // VIOLATION - Formal
+ int otherReallyLongName = -5; // VIOLATION - Local
+ for (int interestingIntIndex = 0; // VIOLATION - For
+ interestingIntIndex < 10;
+ interestingIntIndex ++ ) {
+ }
+ }
+Alternative rule: java:S117
+]]>{0}
'; use the interface instead
+Excessive coupling to implementation types (e.g., HashSet
) limits your ability to use alternate
+implementations in the future as requirements change. Whenever available, declare variables
+and parameters using a more general type (e.g, Set
).
This rule reports uses of concrete collection types. User-defined types that should be treated
+the same as interfaces can be configured with the property allowedTypes
.
import java.util.ArrayList;
+ import java.util.HashSet;
+
+ public class Bar {
+ // sub-optimal approach
+ private ArrayList<SomeType> list = new ArrayList<>();
+
+ public HashSet<SomeType> getFoo() {
+ return new HashSet<SomeType>();
+ }
+
+ // preferred approach
+ private List<SomeType> list = new ArrayList<>();
+
+ public Set<SomeType> getFoo() {
+ return new HashSet<SomeType>();
+ }
+ }
+]]>{0}
' outside of package hierarchy '{1}
' is not recommended; use recommended classes instead
+Avoid using classes from the configured package hierarchy outside of the package hierarchy, +except when using one of the configured allowed classes.
+ package some.package;
+
+ import some.other.package.subpackage.subsubpackage.DontUseThisClass;
+
+ public class Bar {
+ DontUseThisClass boo = new DontUseThisClass();
+ }
+]]>The EJB Specification states that any MessageDrivenBean or SessionBean should be suffixed by 'Bean'.
+ public class SomeBean implements SessionBean{} // proper name
+
+ public class MissingTheProperSuffix implements SessionBean {} // non-standard name
+]]>{0}
' is not assigned and could be declared final
+Reports method and constructor parameters that can be made final because they are never reassigned within the body of the method.
+This rule ignores unused parameters so as not to overlap with the rule {% rule java/bestpractices/UnusedFormalParameter %}. + It will also ignore the parameters of abstract methods.
+ class Foo {
+ // reported, parameter can be declared final
+ public String foo1(String param) {
+ return param;
+ }
+ // not reported, parameter is declared final
+ public String foo2(final String param) {
+ return param.trim();
+ }
+ // not reported because param is unused
+ public String unusedParam(String param) {
+ return "abc";
+ }
+ }
+Alternative rule: java:S1226
+]]>{0}
name '{1}
' doesn't match '{2}
'
+Configurable naming conventions for method declarations. This rule reports + method declarations which do not match the regex that applies to their + specific kind (e.g. JUnit test or native method). Each regex can be + configured through properties.
+By default, this rule uses the standard Java naming convention (Camel case).
+ public class Foo {
+ public void fooStuff() {
+ }
+ }
+Alternative rule: java:S100
+]]>{0}
' may expose an internal array.
+Exposing internal arrays to the caller violates object encapsulation since elements can be +removed or replaced outside of the object that owns it. It is safer to return a copy of the array.
+ public class SecureSystem {
+ UserData [] ud;
+ public UserData [] getUserData() {
+ // Don't return directly the internal array, return a copy
+ return ud;
+ }
+ }
+Alternative rule: java:S2384
+]]>A method should not have the same name as its containing class. +This would be confusing as it would look like a constructor.
+ public class MyClass {
+
+ public MyClass() {} // this is OK because it is a constructor
+
+ public void MyClass() {} // this is bad because it is a method
+ }
+Alternative rule: java:S1223
+]]>{0}
' is null there will be a NullPointerException
+The null check here is misplaced. If the variable is null a NullPointerException
will be thrown.
+Either the check is useless (the variable will never be null
) or it is incorrect.
public class Foo {
+ void bar() {
+ if (a.equals(baz) && a != null) {} // a could be null, misplaced null check
+
+ if (a != null && a.equals(baz)) {} // correct null check
+ }
+ }
+ public class Foo {
+ void bar() {
+ if (a.equals(baz) || a == null) {} // a could be null, misplaced null check
+
+ if (a == null || a.equals(baz)) {} // correct null check
+ }
+ }
+Alternative rules: java:S1697, java:S2259
+]]>{0}
' is missing an @Override annotation.
+Annotating overridden methods with @Override ensures at compile time that + the method really overrides one, which helps refactoring and clarifies intent.
+ public class Foo implements Runnable {
+ // This method is overridden, and should have an @Override annotation
+ public void run() {
+
+ }
+ }
+]]>Serializable classes should provide a serialVersionUID field. +The serialVersionUID field is also needed for abstract base classes. Each individual class in the inheritance +chain needs an own serialVersionUID field. See also Should an abstract class have a serialVersionUID.
+ public class Foo implements java.io.Serializable {
+ String name;
+ // Define serialization id to avoid serialization related bugs
+ // i.e., public static final long serialVersionUID = 4328743;
+ }
+Alternative rule: java:S2057
+]]>A class that has private constructors and does not have any static methods or fields cannot be used.
+When one of the private constructors is annotated with one of the annotations, then the class is not considered
+non-instantiatable anymore and no violation will be reported.
+See the property annotations
.
// This class is unusable, since it cannot be
+ // instantiated (private constructor),
+ // and no static method can be called.
+
+ public class Foo {
+ private Foo() {}
+ void foo() {}
+ }
+]]>Normally only one logger is used in each class. This rule supports slf4j, log4j, Java Util Logging and +log4j2 (since 6.19.0).
+ public class Foo {
+ Logger log = Logger.getLogger(Foo.class.getName());
+ // It is very rare to see two loggers on a class, normally
+ // log information is multiplexed by levels
+ Logger log2= Logger.getLogger(Foo.class.getName());
+ }
+Alternative rule: java:S1312
+]]>Non-private static fields should be made constants (or immutable references) by +declaring them final.
+Non-private non-final static fields break encapsulation and can lead to hard to find +bugs, since these fields can be modified from anywhere within the program. +Callers can trivially access and modify non-private non-final static fields. Neither +accesses nor modifications can be guarded against, and newly set values cannot +be validated.
+If you are using this rule, then you don't need this +rule {% rule java/errorprone/AssignmentToNonFinalStatic %}.
+ public class Greeter { public static Foo foo = new Foo(); ... } // avoid this
+ public class Greeter { public static final Foo FOO = new Foo(); ... } // use this instead
+]]>{0}
'{1}
' has an NPath complexity of {2}
, current threshold is {3}
+The NPath complexity of a method is the number of acyclic execution paths through that method.
+While cyclomatic complexity counts the number of decision points in a method, NPath counts the number of
+full paths from the beginning to the end of the block of the method. That metric grows exponentially, as
+it multiplies the complexity of statements in the same block. For more details on the calculation, see the
+documentation NPATH
.
A threshold of 200 is generally considered the point where measures should be taken to reduce +complexity and increase readability.
+ public class Foo {
+ public static void bar() { // Ncss = 252: reported!
+ boolean a, b = true;
+ try { // 2 * 2 + 2 = 6
+ if (true) { // 2
+ List buz = new ArrayList();
+ }
+
+ for(int i = 0; i < 19; i++) { // * 2
+ List buz = new ArrayList();
+ }
+ } catch(Exception e) {
+ if (true) { // 2
+ e.printStackTrace();
+ }
+ }
+
+ while (j++ < 20) { // * 2
+ List buz = new ArrayList();
+ }
+
+ switch(j) { // * 7
+ case 1:
+ case 2: break;
+ case 3: j = 5; break;
+ case 4: if (b && a) { bar(); } break;
+ default: break;
+ }
+
+ do { // * 3
+ List buz = new ArrayList();
+ } while (a && j++ < 30);
+ }
+ }
+]]>{0}
'{1}
' has a NCSS line count of {2}
.
+This rule uses the NCSS (Non-Commenting Source Statements) metric to determine the number of lines
+of code in a class, method or constructor. NCSS ignores comments, blank lines, and only counts actual
+statements. For more details on the calculation, see the documentation
+NCSS
.
import java.util.Collections; // +0
+ import java.io.IOException; // +0
+
+ class Foo { // +1, total Ncss = 12
+
+ public void bigMethod() // +1
+ throws IOException {
+ int x = 0, y = 2; // +1
+ boolean a = false, b = true; // +1
+
+ if (a || b) { // +1
+ try { // +1
+ do { // +1
+ x += 2; // +1
+ } while (x < 12);
+
+ System.exit(0); // +1
+ } catch (IOException ioe) { // +1
+ throw new PatheticFailException(ioe); // +1
+ }
+ } else {
+ assert false; // +1
+ }
+ }
+ }
+]]>Detects when a class, interface, enum or annotation does not have a package definition.
+ // no package declaration
+ public class ClassInDefaultPackage {
+ }
+Alternative rule: java:S1220
+]]>A non-case label (e.g. a named break/continue label) was present in a switch statement or switch expression. +This is legal, but confusing. It is easy to mix up the case labels and the non-case labels.
+Note: This rule was renamed from NonCaseLabelInSwitchStatement
with PMD 7.7.0.
public class Foo {
+ void bar(int a) {
+ switch (a) {
+ case 1:
+ // do something
+ mylabel: // this is legal, but confusing!
+ break;
+ default:
+ break;
+ }
+ }
+ }
+]]>Switch statements should be exhaustive, to make their control flow
+ easier to follow. This can be achieved by adding a default
case, or,
+ if the switch is on an enum type, by ensuring there is one switch branch
+ for each enum constant.
This rule doesn't consider Switch Statements, that use Pattern Matching, since for these the + compiler already ensures that all cases are covered. The same is true for Switch Expressions, + which are also not considered by this rule.
+ class Foo {{
+ int x = 2;
+ switch (x) {
+ case 1: int j = 6;
+ case 2: int j = 8;
+ // missing default: here
+ }
+ }}
+]]>{0}
' of serializable class '{1}
' is of non-serializable type '{2}
'.
+If a class is marked as Serializable
, then all fields need to be serializable as well. In order to exclude
+a field, it can be marked as transient. Static fields are not considered.
This rule reports all fields, that are not serializable.
+If a class implements the methods to perform manual serialization (writeObject
, readObject
) or uses
+a replacement object (writeReplace
, readResolve
) then this class is ignored.
Note: This rule has been revamped with PMD 6.52.0. It was previously called "BeanMembersShouldSerialize".
+The property prefix
has been deprecated, since in a serializable class all fields have to be
+serializable regardless of the name.
class Buzz implements java.io.Serializable {
+ private static final long serialVersionUID = 1L;
+
+ private transient int someFoo; // good, it's transient
+ private static int otherFoo; // also OK, it's static
+ private java.io.FileInputStream stream; // bad - FileInputStream is not serializable
+
+ public void setStream(FileInputStream stream) {
+ this.stream = stream;
+ }
+
+ public int getSomeFoo() {
+ return this.someFoo;
+ }
+ }
+]]>A non-static initializer block will be called any time a constructor is invoked (just prior to +invoking the constructor). While this is a valid language construct, it is rarely used and is +confusing.
+ public class MyClass {
+ // this block gets run before any call to a constructor
+ {
+ System.out.println("I am about to construct myself");
+ }
+ }
+Alternative rule: java:S1171
+]]>Non-thread safe singletons can result in bad state changes. Eliminate +static singletons if possible by instantiating the object directly. Static +singletons are usually not needed as only a single instance exists anyway. +Other possible fixes are to synchronize the entire method or to use an +initialize-on-demand holder class.
+Refrain from using the double-checked locking pattern. The Java Memory Model doesn't
+guarantee it to work unless the variable is declared as volatile
, adding an uneeded
+performance penalty. Reference
See Effective Java, item 48.
+ private static Foo foo = null;
+
+ //multiple simultaneous callers may see partially initialized objects
+ public static Foo getFoo() {
+ if (foo==null) {
+ foo = new Foo();
+ }
+ return foo;
+ }
+Alternative rule: java:S2444
+]]>Assigning a "null" to a variable (outside of its declaration) is usually bad form. Sometimes, this type +of assignment is an indication that the programmer doesn't completely understand what is going on in the code.
+NOTE: This sort of assignment may used in some cases to dereference objects and encourage garbage collection.
+ public void bar() {
+ Object x = null; // this is OK
+ x = new Object();
+ // big, complex piece of code here
+ x = null; // this is not required
+ // big, complex piece of code here
+ }
+]]>Java allows the use of several variables declaration of the same type on one line. +However, it can lead to quite messy code. This rule looks for several declarations on the same line.
+ String name; // separate declarations
+ String lastname;
+
+ String name, lastname; // combined declaration, a violation
+
+ String name,
+ lastname; // combined declaration on multiple lines, no violation by default.
+ // Set property strictMode to true to mark this as violation.
+Alternative rule: java:S122
+]]>A method should have only one exit point, and that should be the last statement in the method.
+ public class OneReturnOnly1 {
+ public String foo(int x) {
+ if (x > 0) {
+ return "hey"; // first exit
+ }
+ return "hi"; // second exit
+ }
+ }
+Alternative rule: java:S1142
+]]>Calls to a collection's toArray(E[])
method should specify a target array of zero size. This allows the JVM
+to optimize the memory allocation and copying as much as possible.
Previous versions of this rule (pre PMD 6.0.0) suggested the opposite, but current JVM implementations +perform always better, when they have full control over the target array. And allocation an array via +reflection is nowadays as fast as the direct allocation.
+See also Arrays of Wisdom of the Ancients
+Note: If you don't need an array of the correct type, then the simple toArray()
method without an array
+is faster, but returns only an array of type Object[]
.
List<Foo> foos = getFoos();
+
+ // much better; this one allows the jvm to allocate an array of the correct size and effectively skip
+ // the zeroing, since each array element will be overridden anyways
+ Foo[] fooArray = foos.toArray(new Foo[0]);
+
+ // inefficient, the array needs to be zeroed out by the jvm before it is handed over to the toArray method
+ Foo[] fooArray = foos.toArray(new Foo[foos.size()]);
+]]>Override both public boolean Object.equals(Object other), and public int Object.hashCode(), or override neither. Even if you are inheriting a hashCode() from a parent class, consider implementing hashCode and explicitly delegating to your superclass.
+ public class Bar { // poor, missing a hashcode() method
+ public boolean equals(Object o) {
+ // do some comparison
+ }
+ }
+
+ public class Baz { // poor, missing an equals() method
+ public int hashCode() {
+ // return some hash value
+ }
+ }
+
+ public class Foo { // perfect, both methods provided
+ public boolean equals(Object other) {
+ // do some comparison
+ }
+ public int hashCode() {
+ // return some hash value
+ }
+ }
+Alternative rule: java:S1206
+]]>Detects when a package definition contains uppercase characters.
+ package com.MyCompany; // should be lowercase name
+
+ public class SomeClass {
+ }
+Alternative rule: java:S120
+]]>{0}
' can be moved closer to its usages
+Checks for variables that are defined before they might be used. A declaration is +deemed to be premature if there are some statements that may return or throw an +exception between the time the variable is declared and the time it is first read.
+Some variables cannot be declared close to their first usage because of side-effects +occurring before they're first used. We try to avoid reporting those by considering +most method and constructor invocations to be impure. See the second example.
+Note that this rule is meant to improve code readability but is not an optimization. +A smart JIT will not care whether the variable is declared prematurely or not, as it +can reorder code.
+ public int getLength(String[] strings) {
+
+ int length = 0; // could be moved closer to the loop
+
+ if (strings == null || strings.length == 0) return 0;
+
+ for (String str : strings) {
+ length += str.length();
+ }
+
+ return length;
+ }
+ public int getLength(String[] strings) {
+
+ int startTime = System.nanoTime(); // cannot be moved because initializer is impure
+
+ if (strings == null || strings.length == 0) {
+ // some error logic
+ throw new SomeException(...);
+ }
+
+ for (String str : strings) {
+ length += str.length();
+ }
+
+ return System.nanoTime() - startTime;
+ }
+Alternative rule: java:S1941
+]]>{0}
' on all code paths
+Reports exceptions that are thrown from within a catch block, yet don't refer to the +exception parameter declared by that catch block. The stack trace of the original +exception could be lost, which makes the thrown exception less informative.
+To preserve the stack trace, the original exception may be used as the cause of
+the new exception, using Throwable#initCause
, or passed as a constructor argument
+to the new exception. It may also be preserved using Throwable#addSuppressed
.
+The rule actually assumes that any method or constructor that takes the original
+exception as argument preserves the original stack trace.
The rule allows InvocationTargetException
and PrivilegedActionException
to be
+replaced by their cause exception. The discarded part of the stack trace is in those
+cases only JDK-internal code, which is not very useful. The rule also ignores exceptions
+whose name starts with ignored
.
public class Foo {
+ void good() {
+ try{
+ Integer.parseInt("a");
+ } catch (Exception e) {
+ throw new Exception(e); // Ok, this initializes the cause of the new exception
+ }
+ try {
+ Integer.parseInt("a");
+ } catch (Exception e) {
+ throw (IllegalStateException)new IllegalStateException().initCause(e); // second possibility to create exception chain.
+ }
+ }
+ void wrong() {
+ try{
+ Integer.parseInt("a");
+ } catch (Exception e) {
+ // Violation: this only preserves the message and not the stack trace
+ throw new Exception(e.getMessage());
+ }
+ }
+ }
+Alternative rule: java:S1166
+]]>new <code>{0}</code>(...)
, prefer <code>{0}</code>.valueOf(...)
+Reports usages of primitive wrapper constructors. They are deprecated
+ since Java 9 and should not be used. Even before Java 9, they can
+ be replaced with usage of the corresponding static valueOf
factory method
+ (which may be automatically inserted by the compiler since Java 1.5).
+ This has the advantage that it may reuse common instances instead of creating
+ a new instance each time.
Note that for Boolean
, the named constants Boolean.TRUE
and Boolean.FALSE
+ are preferred instead of Boolean.valueOf
.
public class Foo {
+ private Integer ZERO = new Integer(0); // violation
+ private Integer ZERO1 = Integer.valueOf(0); // better
+ private Integer ZERO1 = 0; // even better
+ }
+]]>Object clone() should be implemented with super.clone().
+ class Foo{
+ public Object clone(){
+ return new Foo(); // This is bad
+ }
+ }
+Alternative rule: java:S1182
+]]>A logger should normally be defined private static final and be associated with the correct class.
+private final Log log;
is also allowed for rare cases where loggers need to be passed around,
+with the restriction that the logger needs to be passed into the constructor.
public class Foo {
+
+ private static final Log LOG = LogFactory.getLog(Foo.class); // proper way
+
+ protected Log LOG = LogFactory.getLog(Testclass.class); // wrong approach
+ }
+Alternative rule: java:S1312
+]]>Java will initialize fields with known default values so any explicit initialization of those same defaults +is redundant and results in a larger class file (approximately three additional bytecode instructions per field).
+ public class C {
+ boolean b = false; // examples of redundant initializers
+ byte by = 0;
+ short s = 0;
+ char c = 0;
+ int i = 0;
+ long l = 0;
+
+ float f = .0f; // all possible float literals
+ double d = 0d; // all possible double literals
+ Object o = null;
+
+ MyClass mca[] = null;
+ int i1 = 0, ia1[] = null;
+
+ class Nested {
+ boolean b = false;
+ }
+ }
+]]>Remote Interface of a Session EJB should not have a suffix.
+ /* Poor Session suffix */
+ public interface BadSuffixSession extends javax.ejb.EJBObject {}
+
+ /* Poor EJB suffix */
+ public interface BadSuffixEJB extends javax.ejb.EJBObject {}
+
+ /* Poor Bean suffix */
+ public interface BadSuffixBean extends javax.ejb.EJBObject {}
+]]>A Remote Home interface type of a Session EJB should be suffixed by 'Home'.
+ public interface MyBeautifulHome extends javax.ejb.EJBHome {} // proper name
+
+ public interface MissingProperSuffix extends javax.ejb.EJBHome {} // non-standard name
+]]>Consider replacing Enumeration usages with the newer java.util.Iterator
+ public class Foo implements Enumeration {
+ private int x = 42;
+ public boolean hasMoreElements() {
+ return true;
+ }
+ public Object nextElement() {
+ return String.valueOf(i++);
+ }
+ }
+Alternative rule: java:S1150
+]]>Consider replacing Hashtable usage with the newer java.util.Map if thread safety is not required.
+ public class Foo {
+ void bar() {
+ Hashtable h = new Hashtable();
+ }
+ }
+Alternative rule: java:S1149
+]]>Consider replacing Vector usages with the newer java.util.ArrayList if expensive thread-safe operations are not required.
+ import java.util.Vector;
+ public class Foo {
+ void bar() {
+ Vector v = new Vector();
+ }
+ }
+Alternative rule: java:S1149
+]]>For any method that returns an collection (such as an array, Collection or Map), it is better to return +an empty one rather than a null reference. This removes the need for null checking all results and avoids +inadvertent NullPointerExceptions.
+See Effective Java, 3rd Edition, Item 54: Return empty collections or arrays instead of null
+ public class Example {
+ // Not a good idea...
+ public int[] badBehavior() {
+ // ...
+ return null;
+ }
+
+ // Good behavior
+ public String[] bonnePratique() {
+ //...
+ return new String[0];
+ }
+ }
+]]>Avoid returning from a finally block, this can discard exceptions.
+ public class Bar {
+ public String foo() {
+ try {
+ throw new Exception( "My Exception" );
+ } catch (Exception e) {
+ throw e;
+ } finally {
+ return "A. O. K."; // return not recommended here
+ }
+ }
+ }
+Alternative rule: java:S1143
+]]>{0}
+Short Classnames with fewer than e.g. five characters are not recommended.
+ public class Foo {
+ }
+Alternative rule: java:S101
+]]>Method names that are very short are not helpful to the reader.
+ public class ShortMethod {
+ public void a( int i ) { // Violation
+ }
+ }
+Alternative rule: java:S100
+]]>{0}
+Fields, local variables, enum constant names or parameter names that are very short are not helpful to the reader.
+ public class Something {
+ private int q = 15; // field - too short
+ public static void main( String as[] ) { // formal arg - too short
+ int r = 20 + q; // local var - too short
+ for (int i = 0; i < 10; i++) { // not a violation (inside 'for' loop)
+ r += q;
+ }
+ for (Integer i : numbers) { // not a violation (inside 'for-each' loop)
+ r += q;
+ }
+ }
+ }
+Alternative rule: java:S117
+]]>A method/constructor shouldn't explicitly throw the generic java.lang.Exception, since it +is unclear which exceptions that can be thrown from the methods. It might be +difficult to document and understand such vague interfaces. Use either a class +derived from RuntimeException or a checked exception.
+ public void foo() throws Exception {
+ }
+Alternative rule: java:S112
+]]>Be sure to specify a Locale when creating SimpleDateFormat instances to ensure that locale-appropriate +formatting is used.
+ public class Foo {
+ // Should specify Locale.US (or whatever)
+ private SimpleDateFormat sdf = new SimpleDateFormat("pattern");
+ }
+]]>{0}
+Reports test assertions that may be simplified using a more specific + assertion method. This enables better error messages, and makes the + assertions more readable.
+ import org.junit.Test;
+ import static org.junit.Assert.*;
+
+ class SomeTestClass {
+ Object a,b;
+ @Test
+ void testMethod() {
+ assertTrue(a.equals(b)); // could be assertEquals(a, b);
+ assertTrue(!a.equals(b)); // could be assertNotEquals(a, b);
+
+ assertTrue(!something); // could be assertFalse(something);
+ assertFalse(!something); // could be assertTrue(something);
+
+ assertTrue(a == b); // could be assertSame(a, b);
+ assertTrue(a != b); // could be assertNotSame(a, b);
+
+ assertTrue(a == null); // could be assertNull(a);
+ assertTrue(a != null); // could be assertNotNull(a);
+ }
+ }
+]]>Reports ternary expression with the form condition ? literalBoolean : foo
+or condition ? foo : literalBoolean
.
These expressions can be simplified as follows:
+condition ? true : expr
simplifies to condition || expr
condition ? false : expr
simplifies to !condition && expr
condition ? expr : true
simplifies to !condition || expr
condition ? expr : false
simplifies to condition && expr
public class Foo {
+ public boolean test() {
+ return condition ? true : something(); // can be as simple as return condition || something();
+ }
+
+ public void test2() {
+ final boolean value = condition ? false : something(); // can be as simple as value = !condition && something();
+ }
+
+ public boolean test3() {
+ return condition ? something() : true; // can be as simple as return !condition || something();
+ }
+
+ public void test4() {
+ final boolean otherValue = condition ? something() : false; // can be as simple as condition && something();
+ }
+
+ public boolean test5() {
+ return condition ? true : false; // can be as simple as return condition;
+ }
+ }
+]]>Avoid unnecessary comparisons in boolean expressions, they serve no purpose and impacts readability.
+ public class Bar {
+ // can be simplified to
+ // bar = isFoo();
+ private boolean bar = (isFoo() == true);
+
+ public isFoo() { return false;}
+ }
+Alternative rule: java:S1125
+]]><code>{0}</code>
+Avoid unnecessary if-then-else statements when returning a boolean. The result of +the conditional test can be returned instead.
+ public boolean isBarEqualTo(int x) {
+ if (bar == x) { // this bit of code...
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ public boolean isBarEqualTo(int x) {
+ return bar == x; // can be replaced with this
+ }
+Alternative rule: java:S1126
+]]>No need to check for null before an instanceof; the instanceof keyword returns false when given a null argument.
+ class Foo {
+ void bar(Object x) {
+ if (x != null && x instanceof Bar) {
+ // just drop the "x != null" check
+ }
+ }
+ }
+]]>Some classes contain overloaded getInstance. The problem with overloaded getInstance methods +is that the instance created using the overloaded method is not cached and so, +for each call and new objects will be created for every invocation.
+ public class Singleton {
+
+ private static Singleton singleton = new Singleton( );
+
+ private Singleton(){ }
+
+ public static Singleton getInstance( ) {
+ return singleton;
+ }
+
+ public static Singleton getInstance(Object obj){
+ Singleton singleton = (Singleton) obj;
+ return singleton; //violation
+ }
+ }
+]]>A singleton class should only ever have one instance. Failure to check + whether an instance has already been created may result in multiple + instances being created.
+ class Singleton {
+ private static Singleton instance = null;
+ public static Singleton getInstance() {
+ synchronized(Singleton.class) {
+ return new Singleton(); // this should be assigned to the field
+ }
+ }
+ }
+]]>{0}
' could be replaced by a local variable.
+Reports fields which may be converted to a local variable. This is so because +in every method where the field is used, it is assigned before it is first read. +Hence, the value that the field had before the method call may not be observed, +so it might as well not be stored in the enclosing object.
+Limitations:
+ignoredAnnotations
property). public class Foo {
+ private int x; // this will be reported
+
+ public int foo(int y) {
+ x = y + 5; // assigned before any read
+ return x;
+ }
+
+ public int fooOk(int y) {
+ int z = y + 5; // might as well be a local like here
+ return z;
+ }
+ }
+]]>According to the J2EE specification, an EJB should not have any static fields +with write access. However, static read-only fields are allowed. This ensures proper +behavior especially when instances are distributed by the container on several JREs.
+ public class SomeEJB extends EJBObject implements EJBLocalHome {
+
+ private static int CountA; // poor, field can be edited
+
+ private static final int CountB; // preferred, read-only access
+ }
+]]>new StringBuilder()
or new StringBuffer()
is implicitly converted from char to int
+Individual character values provided as initialization arguments will be converted into integers. +This can lead to internal buffer sizes that are larger than expected. Some examples:
+ new StringBuffer() // 16
+ new StringBuffer(6) // 6
+ new StringBuffer("hello world") // 11 + 16 = 27
+ new StringBuffer('A') // chr(A) = 65
+ new StringBuffer("A") // 1 + 16 = 17
+
+ new StringBuilder() // 16
+ new StringBuilder(6) // 6
+ new StringBuilder("hello world") // 11 + 16 = 27
+ new StringBuilder('C') // chr(C) = 67
+ new StringBuilder("A") // 1 + 16 = 17
+ // misleading instantiation, these buffers
+ // are actually sized to 99 characters long
+ StringBuffer sb1 = new StringBuffer('c');
+ StringBuilder sb2 = new StringBuilder('c');
+
+ // in these forms, just single characters are allocated
+ StringBuffer sb3 = new StringBuffer("c");
+ StringBuilder sb4 = new StringBuilder("c");
+Alternative rule: java:S1317
+]]>Avoid instantiating String objects; this is usually unnecessary since they are immutable and can be safely shared.
+ private String bar = new String("bar"); // just do a String bar = "bar";
+]]>Avoid calling toString() on objects already known to be string instances; this is unnecessary.
+ private String baz() {
+ String bar = "howdy";
+ return bar.toString();
+ }
+Alternative rule: java:S1858
+]]>The method name and parameter number are suspiciously close to Object.equals
, which can denote an
+intention to override it. However, the method does not override Object.equals
, but overloads it instead.
+Overloading Object.equals
method is confusing for other programmers, error-prone and hard to maintain,
+especially when using inheritance, because @Override
annotations used in subclasses can provide a false
+sense of security. For more information on Object.equals
method, see Effective Java, 3rd Edition,
+Item 10: Obey the general contract when overriding equals.
public class Foo {
+ public int equals(Object o) {
+ // oops, this probably was supposed to be boolean equals
+ }
+ public boolean equals(String s) {
+ // oops, this probably was supposed to be equals(Object)
+ }
+ public boolean equals(Object o1, Object o2) {
+ // oops, this probably was supposed to be equals(Object)
+ }
+ }
+Alternative rule: java:S1201
+]]>The method name and return type are suspiciously close to hashCode(), which may denote an intention +to override the hashCode() method.
+ public class Foo {
+ public int hashcode() { // oops, this probably was supposed to be 'hashCode'
+ }
+ }
+Alternative rule: java:S1221
+]]>{0}
+A suspicious octal escape sequence was found inside a String literal. +The Java language specification (section 3.10.6) says an octal +escape sequence inside a literal String shall consist of a backslash +followed by:
+OctalDigit | OctalDigit OctalDigit | ZeroToThree OctalDigit OctalDigit
+Any octal escape sequence followed by non-octal digits can be confusing, +e.g. "\038" is interpreted as the octal escape sequence "\03" followed by +the literal character "8".
+ public void foo() {
+ // interpreted as octal 12, followed by character '8'
+ System.out.println("suspicious: \128");
+ }
+]]>A high ratio of statements to labels in a switch statement implies that the switch statement +is overloaded. Consider moving the statements into new methods or creating subclasses based +on the switch variable.
+ public class Foo {
+ public void bar(int x) {
+ switch (x) {
+ case 1: {
+ // lots of statements
+ break;
+ } case 2: {
+ // lots of statements
+ break;
+ }
+ }
+ }
+ }
+Alternative rule: java:S1151
+]]>References to System.(out|err).print are usually intended for debugging purposes and can remain in +the codebase even in production code. By using a logger one can enable/disable this behaviour at +will (and by priority) and avoid clogging the Standard out log.
+ class Foo{
+ Logger log = Logger.getLogger(Foo.class.getName());
+ public void testA () {
+ System.out.println("Entering test");
+ // Better use this
+ log.fine("Entering test");
+ }
+ }
+Alternative rule: java:S106
+]]>{0}
' might be a test class, but it contains no test cases.
+Test classes typically end with the suffix "Test", "Tests" or "TestCase". Having a non-test class with that name
+is not a good practice, since most people will assume it is a test case. Test classes have test methods
+named "testXXX" (JUnit3) or use annotations (e.g. @Test
).
The suffix can be configured using the property testClassPattern
. To disable the detection of possible test classes
+by name, set this property to an empty string.
//Consider changing the name of the class if it is not a test
+ //Consider adding test methods if it is a test
+ public class CarTest {
+ public static void main(String[] args) {
+ // do something
+ }
+ // code
+ }
+]]>Switch statements are intended to be used to support complex branching behaviour. Using a switch for only a few +cases is ill-advised, since switches are not as easy to understand as if-else statements. In these cases use the +if-else statement to increase code readability.
+Note: This rule was named TooFewBranchesForASwitchStatement before PMD 7.7.0.
+ // With a minimumNumberCaseForASwitch of 3
+ public class Foo {
+ public void bar(int condition) {
+ switch (condition) {
+ case 1:
+ instruction;
+ break;
+ default:
+ break; // not enough for a 'switch' stmt, a simple 'if' stmt would have been more appropriate
+ }
+ }
+ }
+]]>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.
+ public class Person { // too many separate fields
+ int birthYear;
+ int birthMonth;
+ int birthDate;
+ float height;
+ float weight;
+ }
+
+ public class Person { // this is more manageable
+ Date birthDate;
+ BodyMeasurements measurements;
+ }
+]]>A class with too many methods is probably a good suspect for refactoring, in order to reduce its +complexity and find a way to have more fine grained objects.
+Alternative rule: java:S1448
+]]>If you overuse the static import feature, it can make your program unreadable and +unmaintainable, polluting its namespace with all the static members you import. +Readers of your code (including you, a few months after you wrote it) will not know +which class a static member comes from (Sun 1.5 Language Guide).
+ import static Lennon;
+ import static Ringo;
+ import static George;
+ import static Paul;
+ import static Yoko; // Too much !
+]]>Uncommented Empty Constructor finds instances where a constructor does not +contain statements, but there is no comment. By explicitly commenting empty +constructors it is easier to distinguish between intentional (commented) +and unintentional empty constructors.
+ public Foo() {
+ // This constructor is intentionally empty. Nothing special is needed here.
+ }
+Alternative rule: java:S2094
+]]>Uncommented Empty Method Body finds instances where a method body does not contain +statements, but there is no comment. By explicitly commenting empty method bodies +it is easier to distinguish between intentional (commented) and unintentional +empty methods.
+ public void doSomething() {
+ }
+Alternative rule: java:S1186
+]]>Do not use "if" statements whose conditionals are always true or always false.
+ public class Foo {
+ public void close() {
+ if (true) { // fixed conditional, not recommended
+ // ...
+ }
+ }
+ }
+Alternative rule: java:S2583
+]]>Unit assertions should include an informative message - i.e., use the three-argument version of
+assertEquals()
, not the two-argument version.
This rule supports tests using JUnit (3, 4 and 5) and TestNG.
+Note: This rule was named JUnitAssertionsShouldIncludeMessage before PMD 7.7.0.
+ public class Foo {
+ @Test
+ public void testSomething() {
+ assertEquals("foo", "bar");
+ // Use the form:
+ // assertEquals("Foo does not equals bar", "foo", "bar");
+ // instead
+ }
+ }
+]]>Unit tests should not contain too many asserts. Many asserts are indicative of a complex test, for which + it is harder to verify correctness. Consider breaking the test scenario into multiple, shorter test scenarios. + Customize the maximum number of assertions used by this Rule to suit your needs.
+This rule checks for JUnit (3, 4 and 5) and TestNG Tests.
+Note: This rule was named JUnitTestContainsTooManyAsserts before PMD 7.7.0.
+ public class MyTestCase {
+ // Ok
+ @Test
+ public void testMyCaseWithOneAssert() {
+ boolean myVar = false;
+ assertFalse("should be false", myVar);
+ }
+
+ // Bad, too many asserts (assuming max=1)
+ @Test
+ public void testMyCaseWithMoreAsserts() {
+ boolean myVar = false;
+ assertFalse("myVar should be false", myVar);
+ assertEquals("should equals false", false, myVar);
+ }
+ }
+]]>Unit tests should include at least one assertion. This makes the tests more robust, and using assert + with messages provide the developer a clearer idea of what the test does.
+This rule checks for JUnit (3, 4 and 5) and TestNG Tests.
+Note: This rule was named JUnitTestsShouldIncludeAssert before PMD 7.7.0.
+ public class Foo {
+ @Test
+ public void testSomething() {
+ Bar b = findBar();
+ // This is better than having a NullPointerException
+ // assertNotNull("bar not found", b);
+ b.work();
+ }
+ }
+]]>This rule detects methods called tearDown()
that are not properly annotated as a cleanup method.
+This is primarily intended to assist in upgrading from JUnit 3, where tear down methods were required to be called tearDown()
.
+To a lesser extent, this may help detect omissions even under newer JUnit versions or under TestNG,
+as long as you are following this convention to name the methods.
@After
after running each test.@AfterEach
and @AfterAll
annotations to execute methods after each test or after all tests in the class, respectively.@AfterMethod
and @AfterClass
to execute methods after each test or after tests in the class, respectively.Note: This rule was named JUnit4TestShouldUseAfterAnnotation before PMD 7.7.0.
+ public class MyTest {
+ public void tearDown() {
+ bad();
+ }
+ }
+ public class MyTest2 {
+ @After public void tearDown() {
+ good();
+ }
+ }
+]]>This rule detects methods called setUp()
that are not properly annotated as a setup method.
+This is primarily intended to assist in upgrading from JUnit 3, where setup methods were required to be called setUp()
.
+To a lesser extent, this may help detect omissions even under newer JUnit versions or under TestNG,
+as long as you are following this convention to name the methods.
@Before
before all tests.@BeforeEach
and @BeforeAll
annotations to execute methods before each test or before all tests in the class, respectively.@BeforeMethod
and @BeforeClass
to execute methods before each test or before tests in the class, respectively.Note: This rule was named JUnit4TestShouldUseBeforeAnnotation before PMD 7.7.0.
+ public class MyTest {
+ public void setUp() {
+ bad();
+ }
+ }
+ public class MyTest2 {
+ @Before public void setUp() {
+ good();
+ }
+ }
+]]>The rule will detect any test method starting with "test" that is not properly annotated, and will therefore not be run.
+In JUnit 4, only methods annotated with the @Test
annotation are executed.
+ In JUnit 5, one of the following annotations should be used for tests: @Test
, @RepeatedTest
, @TestFactory
, @TestTemplate
or @ParameterizedTest
.
+ In TestNG, only methods annotated with the @Test
annotation are executed.
Note: This rule was named JUnit4TestShouldUseTestAnnotation before PMD 7.7.0.
+ public class MyTest {
+ public void testBad() {
+ doSomething();
+ }
+
+ @Test
+ public void testGood() {
+ doSomething();
+ }
+ }
+]]>Avoid the use of value in annotations when it's the only element.
+ @TestClassAnnotation(value = "TEST")
+ public class Foo {
+
+ @TestMemberAnnotation(value = "TEST")
+ private String y;
+
+ @TestMethodAnnotation(value = "TEST")
+ public void bar() {
+ int x = 42;
+ return;
+ }
+ }
+
+ // should be
+
+ @TestClassAnnotation("TEST")
+ public class Foo {
+
+ @TestMemberAnnotation("TEST")
+ private String y;
+
+ @TestMethodAnnotation("TEST")
+ public void bar() {
+ int x = 42;
+ return;
+ }
+ }
+]]>A JUnit test assertion with a boolean literal is unnecessary since it always will evaluate to the same thing.
+Consider using flow control (in case of assertTrue(false)
or similar) or simply removing
+statements like assertTrue(true)
and assertFalse(false)
. If you just want a test to halt after finding
+an error, use the fail()
method and provide an indication message of why it did.
public class SimpleTest extends TestCase {
+ public void testX() {
+ assertTrue(true); // serves no real purpose - remove it
+ }
+ }
+]]>{0}
+Reports explicit boxing and unboxing conversions that may safely be removed, + either because they would be inserted by the compiler automatically, + or because they're semantically a noop (eg unboxing a value to rebox it immediately).
+Note that this only handles boxing and unboxing conversions occurring through
+ calls to valueOf
or one of the intValue
, byteValue
, etc. methods. Casts
+ that command a conversion are reported by {% rule UnnecessaryCast %} instead.
{
+ // Instead of
+ Integer integer = Integer.valueOf(2);
+ // you may just write
+ Integer integer = 2;
+
+ int i = integer.intValue(); // similarly for unboxing
+
+ // Instead of
+ int x = Integer.valueOf("42");
+ // you may just write
+ int x = Integer.parseInt("42");
+ }
+]]>Using equalsIgnoreCase() is faster than using toUpperCase/toLowerCase().equals()
+ boolean answer1 = buz.toUpperCase().equals("BAZ"); // should be buz.equalsIgnoreCase("BAZ")
+
+ boolean answer2 = buz.toUpperCase().equalsIgnoreCase("BAZ"); // another unnecessary toUpperCase()
+Alternative rule: java:S1157
+]]>{0}
)
+Detects casts which could be removed as the operand of the cast is already suitable +for the context type. For instance, in the following: +
Object context = (Comparable) "o";
+The cast is unnecessary. This is because String
already is a subtype of both
+Comparable
and Object
.
+This will also flag casts that can be avoided because of the autoboxing feature of Java 5. +
Integer integer = (Integer) 1;
+The literal would be autoboxed to Integer
anyway.
+ import java.util.function.Function;
+ class SomeClass {
+ static {
+ Object o; long l; int i; Integer boxedInt;
+
+ // reference conversions
+
+ o = (Object) new SomeClass(); // unnecessary
+ o = (SomeClass) o; // necessary (narrowing cast)
+ o = (Comparable<String>) "string"; // unnecessary
+
+ // primitive conversions
+
+ l = (long) 2; // unnecessary
+ l = (long) 2.0; // necessary (narrowing cast)
+ l = (byte) i; // necessary (narrowing cast)
+
+ // boxing/unboxing casts (since java 5)
+
+ o = (Integer) 3; // unnecessary (autoboxing would apply)
+ o = (long) 3; // necessary (would be boxed to Long)
+ l = (int) boxedInt; // necessary (cannot cast Integer to long)
+
+ // casts that give a target type to a lambda/ method ref are necessary
+
+ o = (Function<Integer, String>) Integer::toString; // necessary (no target type)
+ }
+ }
+ import java.util.*;
+ class SomeClass {
+ static {
+ /* Casts involving access to collections were common before Java 5, because collections
+ * were not generic. This rule may hence be useful when converting from using a raw
+ * type like `List` to a parameterized type like `List<String>`.
+ */
+ List<String> stringList = Arrays.asList("a", "b");
+ String element = (String) stringList.get(0); // this cast is unnecessary
+ }
+ }
+]]>This rule detects when a constructor is not necessary; i.e., when there is only one constructor and the +constructor is identical to the default constructor. The default constructor should has same access +modifier as the declaring class. In an enum type, the default constructor is implicitly private.
+ public class Foo {
+ public Foo() {}
+ }
+Alternative rule: java:S1186
+]]>Avoid the use temporary objects when converting primitives to Strings. Use the static conversion methods +on the wrapper classes instead.
+ public String convert(int x) {
+ String foo = new Integer(x).toString(); // this wastes an object
+
+ return Integer.toString(x); // preferred approach
+ }
+Alternative rule: java:S1158
+]]>{0}
': '{1}
' is already in scope{2}
+Import statements allow the use of non-fully qualified names. The use of a fully qualified name +which is covered by an import statement is redundant. Consider using the non-fully qualified name.
+ import java.util.List;
+
+ public class Foo {
+ private java.util.List list1; // Unnecessary FQN
+ private List list2; // More appropriate given import of 'java.util.List'
+ }
+]]>{0}
'
+Reports import statements that can be removed. They are either unused, + duplicated, or the members they import are already implicitly in scope, + because they're in java.lang, or the current package.
+If some imports cannot be resolved, for instance because you run PMD with + an incomplete auxiliary classpath, some imports may be conservatively marked + as used even if they're not to avoid false positives.
+ import java.io.File; // not used, can be removed
+ import java.util.Collections; // used below
+ import java.util.*; // so this one is not used
+
+ import java.lang.Object; // imports from java.lang, unnecessary
+ import java.lang.Object; // duplicate, unnecessary
+
+ public class Foo {
+ static Object emptyList() {
+ return Collections.emptyList();
+ }
+ }
+]]>{0}
'
+Avoid the creation of unnecessary local variables
+ public class Foo {
+ public int foo() {
+ int x = doSomething();
+ return x; // instead, just 'return doSomething();'
+ }
+ }
+Alternative rule: java:S1488
+]]>{0}
on {1}
'{2}
'{3}
+Fields in interfaces and annotations are automatically public static final
, and methods are public abstract
.
+Classes, interfaces or annotations nested in an interface or annotation are automatically public static
+(all nested interfaces and annotations are automatically static).
+Nested enums are automatically static
.
+For historical reasons, modifiers which are implied by the context are accepted by the compiler, but are superfluous.
public @interface Annotation {
+ public abstract void bar(); // both abstract and public are ignored by the compiler
+ public static final int X = 0; // public, static, and final all ignored
+ public static class Bar {} // public, static ignored
+ public static interface Baz {} // ditto
+ }
+ public interface Foo {
+ public abstract void bar(); // both abstract and public are ignored by the compiler
+ public static final int X = 0; // public, static, and final all ignored
+ public static class Bar {} // public, static ignored
+ public static interface Baz {} // ditto
+ }
+ public class Bar {
+ public static interface Baz {} // static ignored
+ public static enum FoorBar { // static ignored
+ FOO;
+ }
+ }
+ public class FooClass {
+ static record BarRecord() {} // static ignored
+ }
+ public interface FooInterface {
+ static record BarRecord() {} // static ignored
+ }
+]]>Avoid the use of unnecessary return statements. A return is unnecessary when no +instructions follow anyway.
+ public class Foo {
+ public void bar() {
+ int x = 42;
+ return;
+ }
+ }
+]]>Reports unnecessary semicolons (so called "empty statements" and "empty declarations"). + These can be removed without changing the program. The Java grammar + allows them for historical reasons, but they should be avoided.
+This rule will not report empty statements that are syntactically + required, for instance, because they are the body of a control statement.
+This rule replaces EmptyStatementNotInLoop.
+ class Foo {
+ {
+ toString();; // one of these semicolons is unnecessary
+ if (true); // this semicolon is not unnecessary, but it could be an empty block instead (not reported)
+ }
+ }; // this semicolon is unnecessary
+]]>Reports explicit array creation when a varargs is expected. + For instance: +
Arrays.asList(new String[] { "foo", "bar", });
+ can be replaced by:
+ Arrays.asList("foo", "bar");
+ import java.util.Arrays;
+
+ class C {
+ static {
+ Arrays.asList(new String[]{"foo", "bar",});
+ // should be
+ Arrays.asList("foo", "bar");
+ }
+ }
+]]>{0}
.
+This rule reports suppression comments and annotations that did not suppress any PMD violation. + Note that violations of this rule cannot be suppressed.
+Please note:
+@SuppressWarnings("PMD")
. For instance @SuppressWarnings("all")
is never reported as we cannot know if another tool is producing a public class Something {
+ // Unless some rule triggered on the following line, this rule will report the comment:
+ private void foo() {} // NOPMD
+ }
+]]>Instances of java.text.Format
are generally not synchronized.
+Sun recommends using separate format instances for each thread.
+If multiple threads must access a static formatter, the formatter must be
+synchronized on block level.
public class Foo {
+ private static final SimpleDateFormat sdf = new SimpleDateFormat();
+ void bar() {
+ sdf.format(); // poor, no thread-safety
+ }
+ void foo() {
+ synchronized (sdf) { // preferred
+ sdf.format();
+ }
+ }
+ }
+]]>Reports assignments to variables that are never used before the variable is overwritten, + or goes out of scope. Unused assignments are those for which + 1. The variable is never read after the assignment, or + 2. The assigned value is always overwritten by other assignments before the next read of + the variable.
+The rule tracks assignements to fields of this
, and static fields of the current class.
+ This may cause some false positives in timing-sensitive concurrent code, which the rule cannot detect.
The rule may be suppressed with the standard @SuppressWarnings("unused")
tag.
The rule subsumes UnusedLocalVariable
, and UnusedFormalParameter
.
+ Those violations are filtered
+ out by default, in case you already have enabled those rules, but may be enabled with the property
+ reportUnusedVariables
. Variables whose name starts with ignored
or unused
are filtered out, as
+ is standard practice for exceptions.
Limitations:
+this(...)
syntax. This may cause false-negatives.Both of those limitations may be partly relaxed in PMD 7.
+ class A {
+ // this field initializer is redundant,
+ // it is always overwritten in the constructor
+ int f = 1;
+
+ A(int f) {
+ this.f = f;
+ }
+ }
+ class B {
+
+ int method(int i, int j) {
+ // this initializer is redundant,
+ // it is overwritten in all branches of the `if`
+ int k = 0;
+
+ // Both the assignments to k are unused, because k is
+ // not read after the if/else
+ // This may hide a bug: the programmer probably wanted to return k
+ if (i < j)
+ k = i;
+ else
+ k = j;
+
+ return j;
+ }
+
+ }
+ class C {
+
+ int method() {
+ int i = 0;
+
+ checkSomething(++i);
+ checkSomething(++i);
+ checkSomething(++i);
+ checkSomething(++i);
+
+ // That last increment is not reported unless
+ // the property `checkUnusedPrefixIncrement` is
+ // set to `true`
+ // Technically it could be written (i+1), but it
+ // is not very important
+ }
+
+ }
+ class C {
+
+ // variables that are truly unused (at most assigned to, but never accessed)
+ // are only reported if property `reportUnusedVariables` is true
+
+ void method(int param) { } // for example this method parameter
+
+ // even then, you can suppress the violation with an annotation:
+
+ void method(@SuppressWarning("unused") int param) { } // no violation, even if `reportUnusedVariables` is true
+
+ // For catch parameters, or for resources which don't need to be used explicitly,
+ // you can give a name that starts with "ignored" to ignore such warnings
+
+ {
+ try (Something ignored = Something.create()) {
+ // even if ignored is unused, it won't be flagged
+ // its purpose might be to side-effect in the create/close routines
+
+ } catch (Exception e) { // this is unused and will cause a warning if `reportUnusedVariables` is true
+ // you should choose a name that starts with "ignored"
+ return;
+ }
+ }
+
+ }
+]]>{0}
parameters such as '{1}
'.
+Reports parameters of methods and constructors that are not referenced them in the method body.
+Parameters whose name starts with ignored
or unused
are filtered out.
Removing unused formal parameters from public methods could cause a ripple effect through the code base.
+Hence, by default, this rule only considers private methods. To include non-private methods, set the
+checkAll
property to true
.
public class Foo {
+ private void bar(String howdy) {
+ // howdy is not used
+ }
+ }
+Alternative rule: java:S1172
+]]>{0}
'.
+Detects when a local variable is declared and/or assigned, but not used.
+Variables whose name starts with ignored
or unused
are filtered out.
public class Foo {
+ public void doSomething() {
+ int i = 5; // Unused
+ }
+ }
+Alternative rule: java:S1481
+]]>After checking an object reference for null, you should invoke equals() on that object rather than passing +it to another object's equals() method.
+ public class Test {
+
+ public String method1() { return "ok";}
+ public String method2() { return null;}
+
+ public void method(String a) {
+ String b;
+ // I don't know it method1() can be "null"
+ // but I know "a" is not null..
+ // I'd better write a.equals(method1())
+
+ if (a!=null && method1().equals(a)) { // will trigger the rule
+ //whatever
+ }
+
+ if (method1().equals(a) && a != null) { // won't trigger the rule
+ //whatever
+ }
+
+ if (a!=null && method1().equals(b)) { // won't trigger the rule
+ //whatever
+ }
+
+ if (a!=null && "LITERAL".equals(a)) { // won't trigger the rule
+ //whatever
+ }
+
+ if (a!=null && !a.equals("go")) { // won't trigger the rule
+ a=method2();
+ if (method1().equals(a)) {
+ //whatever
+ }
+ }
+ }
+ }
+]]>{0}
'.
+Detects when a private field is declared and/or assigned a value, but not used.
+Since PMD 6.50.0 private fields are ignored, if the fields are annotated with any annotation or the +enclosing class has any annotation. Annotations often enable a framework (such as dependency injection, mocking +or e.g. Lombok) which use the fields by reflection or other means. This usage can't be detected by static code analysis. +Previously these frameworks where explicitly allowed by listing their annotations in the property +"ignoredAnnotations", but that turned out to be prone of false positive for any not explicitly considered framework.
+ public class Something {
+ private static int FOO = 2; // Unused
+ private int i = 5; // Unused
+ private int j = 6;
+ public int addOne() {
+ return j++;
+ }
+ }
+Alternative rule: java:S1068
+]]>{0}
'.
+Unused Private Method detects when a private method is declared but is unused.
+ public class Something {
+ private void foo() {} // unused
+ }
+]]>ArrayList is a much better Collection implementation than Vector if thread-safe operation is not required.
+ import java.util.*;
+ public class SimpleTest extends TestCase {
+ public void testX() {
+ Collection c1 = new Vector();
+ Collection c2 = new ArrayList(); // achieves the same with much better performance
+ }
+ }
+Alternative rule: java:S1149
+]]>The java.util.Arrays
class has a asList()
method that should be used when you want to create a new List from
+an array of objects. It is faster than executing a loop to copy all the elements of the array one by one.
Note that the result of Arrays.asList()
is backed by the specified array,
+changes in the returned list will result in the array to be modified.
+For that reason, it is not possible to add new elements to the returned list of Arrays.asList()
+(UnsupportedOperationException).
+You must use new ArrayList<>(Arrays.asList(...))
if that is inconvenient for you (e.g. because of concurrent access).
public class Test {
+ public void foo(Integer[] ints) {
+ // could just use Arrays.asList(ints)
+ List<Integer> l = new ArrayList<>(100);
+ for (int i = 0; i < ints.length; i++) {
+ l.add(ints[i]);
+ }
+
+ List<Integer> anotherList = new ArrayList<>();
+ for (int i = 0; i < ints.length; i++) {
+ anotherList.add(ints[i].toString()); // won't trigger the rule
+ }
+ }
+ }
+]]>The isEmpty() method on java.util.Collection is provided to determine if a collection has any elements. +Comparing the value of size() to 0 does not convey intent as well as the isEmpty() method.
+ public class Foo {
+ void good() {
+ List foo = getList();
+ if (foo.isEmpty()) {
+ // blah
+ }
+ }
+
+ void bad() {
+ List foo = getList();
+ if (foo.size() == 0) {
+ // blah
+ }
+ }
+ }
+Alternative rule: java:S1155
+]]>Since Java5 brought a new implementation of the Map designed for multi-threaded access, you can +perform efficient map reads without blocking other threads.
+ public class ConcurrentApp {
+ public void getMyInstance() {
+ Map map1 = new HashMap(); // fine for single-threaded access
+ Map map2 = new ConcurrentHashMap(); // preferred for use with multiple threads
+
+ // the following case will be ignored by this rule
+ Map map3 = someModule.methodThatReturnMap(); // might be OK, if the returned map is already thread-safe
+ }
+ }
+]]>To make sure the full stacktrace is printed out, use the logging statement with two arguments: a String and a Throwable.
+This rule only applies to Apache Commons Logging.
+ public class Main {
+ private static final Log _LOG = LogFactory.getLog( Main.class );
+ void bar() {
+ try {
+ } catch( Exception e ) {
+ _LOG.error( e ); //Wrong!
+ } catch( OtherException oe ) {
+ _LOG.error( oe.getMessage(), oe ); //Correct
+ }
+ }
+ }
+Alternative rule: java:S1166
+]]><code>{0}</code>
+In some cases, explicit type arguments in a constructor call for a generic type
+may be replaced by diamond type arguments (<>
), and be inferred by the compiler.
+This rule recommends that you use diamond type arguments anywhere possible, since
+it avoids duplication of the type arguments, and makes the code more concise and readable.
This rule is useful when upgrading a codebase to Java 1.7, Java 1.8, or Java 9. +The diamond syntax was first introduced in Java 1.7. In Java 8, improvements in Java's +type inference made more type arguments redundant. In Java 9, type arguments inference +was made possible for anonymous class constructors.
+ import java.util.*;
+ class Foo {
+ static {
+ List<String> strings;
+ strings = new ArrayList<String>(); // unnecessary duplication of type parameters
+ strings = new ArrayList<>(); // using diamond type arguments is more concise
+
+ strings = new ArrayList(); // accidental use of a raw type, you can use ArrayList<> instead
+
+ strings = new ArrayList<>() {
+ // for anonymous classes, this is possible since Java 9 only
+ };
+ }
+ }
+]]>{0}
+Wherever possible, use EnumSet
or EnumMap
instead of HashSet
and HashMap
when the keys
+ are of an enum type. The specialized enum collections are more space- and time-efficient.
+ This rule reports constructor expressions for hash sets or maps whose key
+ type is an enum type.
import java.util.EnumMap;
+ import java.util.HashSet;
+
+ enum Example {
+ A, B, C;
+
+ public static Set<Example> newSet() {
+ return new HashSet<>(); // Could be EnumSet.noneOf(Example.class)
+ }
+
+ public static <V> Map<Example, V> newMap() {
+ return new HashMap<>(); // Could be new EnumMap<>(Example.class)
+ }
+ }
+]]>Using '==' or '!=' to compare strings is only reliable if the interned string (String#intern()
)
+is used on both sides.
Use the equals()
method instead.
public boolean test(String s) {
+ if (s == "one") return true; // unreliable
+ if ("two".equals(s)) return true; // better
+ return false;
+ }
+Alternative rule: java:S1698
+]]>Java 10 introduced the var
keyword. This reduces the amount of code written because java can infer the type
+from the initializer of the variable declaration.
This is essentially a trade-off: On the one hand, it can make code more readable by eliminating redundant
+information. On the other hand, it can make code less readable by eliding useful information. There is no
+blanket rule for when var
should be used or shouldn't.
It may make sense to use var
when the type is inherently clear upon reading the statement
+(ie: assignment to either a literal value or a constructor call). Those use cases
+can be enabled through properties.
Notice that lambda parameters are allowed, as they are already inferred by default (the var
keyword
+is completely optional).
Problem: Use of FileItem.get() +and FileItem.getString() +could exhaust memory since they load the entire file into memory.
+Solution: Use FileItem.getInputStream() +and buffering.
+ import org.apache.commons.fileupload.FileItem;
+
+ public class FileStuff {
+ private String bad(FileItem fileItem) {
+ return fileItem.getString();
+ }
+
+ private InputStream good(FileItem fileItem) {
+ return fileItem.getInputStream();
+ }
+ }
+]]>Use String.indexOf(char) when checking for the index of a single character; it executes faster.
+ String s = "hello world";
+ // avoid this
+ if (s.indexOf("d") {}
+ // instead do this
+ if (s.indexOf('d') {}
+]]>When doing String::toLowerCase()/toUpperCase()
conversions, use an explicit locale argument to specify the case
+transformation rules.
Using String::toLowerCase()
without arguments implicitly uses Locale::getDefault()
.
+The problem is that the default locale depends on the current JVM setup (and usually on the system in which
+it is running). Using the system default may be exactly what you want (e.g. if you are manipulating strings
+you got through standard input), but it may as well not be the case (e.g. if you are getting the string over
+the network or a file, and the encoding is well-defined and independent of the environment). In the latter case,
+using the default locale makes the case transformation brittle, as it may yield unexpected results on a machine
+whose locale has other case translation rules. For example, in Turkish, the uppercase form of i
is İ
(U+0130,
+not ASCII) and not I
(U+0049) as in English.
The rule is intended to force developers to think about locales when dealing with strings. By taking a +conscious decision about the choice of locale at the time of writing, you reduce the risk of surprising +behaviour down the line, and communicate your intent to future readers.
+ // violation - implicitly system-dependent conversion
+ if (x.toLowerCase().equals("list")) {}
+
+ // The above will not match "LIST" on a system with a Turkish locale.
+ // It could be replaced with
+ if (x.toLowerCase(Locale.US).equals("list")) { }
+ // or simply
+ if (x.equalsIgnoreCase("list")) { }
+
+ // ok - system independent conversion
+ String z = a.toLowerCase(Locale.ROOT);
+
+ // ok - explicit system-dependent conversion
+ String z2 = a.toLowerCase(Locale.getDefault());
+]]>Thread.notify() awakens a thread monitoring the object. If more than one thread is monitoring, then only +one is chosen. The thread chosen is arbitrary; thus it's usually safer to call notifyAll() instead.
+ void bar() {
+ x.notify();
+ // If many threads are monitoring x, only one (and you won't know which) will be notified.
+ // use instead:
+ x.notifyAll();
+ }
+Alternative rule: java:S2446
+]]>When you write a public method, you should be thinking in terms of an API. If your method is public, it means other class +will use it, therefore, you want (or need) to offer a comprehensive and evolutive API. If you pass a lot of information +as a simple series of Strings, you may think of using an Object to represent all those information. You'll get a simpler +API (such as doWork(Workload workload), rather than a tedious series of Strings) and more importantly, if you need at some +point to pass extra data, you'll be able to do so by simply modifying or extending Workload without any modification to +your API.
+ public class MyClass {
+ public void connect(String username,
+ String pssd,
+ String databaseName,
+ String databaseAdress)
+ // Instead of those parameters object
+ // would ensure a cleaner API and permit
+ // to add extra data transparently (no code change):
+ // void connect(UserData data);
+ {
+
+ }
+ }
+Alternative rule: java:S107
+]]>In J2EE, the getClassLoader() method might not work as expected. Use +Thread.currentThread().getContextClassLoader() instead.
+ public class Foo {
+ ClassLoader cl = Bar.class.getClassLoader();
+ }
+]]>When declaring and initializing array fields or variables, it is not necessary to explicitly create a new array
+using new
. Instead one can simply define the initial content of the array as a expression in curly braces.
E.g. int[] x = new int[] { 1, 2, 3 };
can be written as int[] x = { 1, 2, 3 };
.
Foo[] x = new Foo[] { ... }; // Overly verbose
+ Foo[] x = { ... }; //Equivalent to above line
+]]>Starting with Java 7, StandardCharsets provides constants for common Charset objects, such as UTF-8.
+Using the constants is less error prone, and can provide a small performance advantage compared to Charset.forName(...)
+since no scan across the internal Charset
caches is needed.
public class UseStandardCharsets {
+ public void run() {
+
+ // looking up the charset dynamically
+ try (OutputStreamWriter osw = new OutputStreamWriter(out, Charset.forName("UTF-8"))) {
+ osw.write("test");
+ }
+
+ // best to use StandardCharsets
+ try (OutputStreamWriter osw = new OutputStreamWriter(out, StandardCharsets.UTF_8)) {
+ osw.write("test");
+ }
+ }
+ }
+]]>The use of the '+=' operator for appending strings causes the JVM to create and use an internal StringBuffer. +If a non-trivial number of these concatenations are being used then the explicit use of a StringBuilder or +threadsafe StringBuffer is recommended to avoid this.
+ public class Foo {
+ String inefficientConcatenation() {
+ String result = "";
+ for (int i = 0; i < 10; i++) {
+ // warning: this concatenation will create one new StringBuilder per iteration
+ result += getStringFromSomeWhere(i);
+ }
+ return result;
+ }
+
+ String efficientConcatenation() {
+ // better would be to use one StringBuilder for the entire loop
+ StringBuilder result = new StringBuilder();
+ for (int i = 0; i < 10; i++) {
+ result.append(getStringFromSomeWhere(i));
+ }
+ return result.toString();
+ }
+ }
+]]>Use StringBuffer.length() to determine StringBuffer length rather than using StringBuffer.toString().equals("") +or StringBuffer.toString().length() == ...
+ StringBuffer sb = new StringBuffer();
+
+ if (sb.toString().equals("")) {} // inefficient
+
+ if (sb.length() == 0) {} // preferred
+]]>Java 7 introduced the try-with-resources statement. This statement ensures that each resource is closed at the end
+of the statement. It avoids the need of explicitly closing the resources in a finally block. Additionally exceptions
+are better handled: If an exception occurred both in the try
block and finally
block, then the exception from
+the try block was suppressed. With the try
-with-resources statement, the exception thrown from the try-block is
+preserved.
public class TryWithResources {
+ public void run() {
+ InputStream in = null;
+ try {
+ in = openInputStream();
+ int i = in.read();
+ } catch (IOException e) {
+ e.printStackTrace();
+ } finally {
+ try {
+ if (in != null) in.close();
+ } catch (IOException ignored) {
+ // ignored
+ }
+ }
+
+ // better use try-with-resources
+ try (InputStream in2 = openInputStream()) {
+ int i = in2.read();
+ }
+ }
+ }
+]]>{0}
should separate every third digit with an underscore
+Since Java 1.7, numeric literals can use underscores to separate digits. This rule enforces that + numeric literals above a certain length use these underscores to increase readability.
+The rule only supports decimal (base 10) literals for now. The acceptable length under which literals + are not required to have underscores is configurable via a property. Even under that length, underscores + that are misplaced (not making groups of 3 digits) are reported.
+ public class Foo {
+ private int num = 1000000; // should be 1_000_000
+ }
+]]>For classes that only have static methods, consider making them utility classes. +Note that this doesn't apply to abstract classes, since their subclasses may +well include non-static methods. Also, if you want this class to be a utility class, +remember to add a private constructor to prevent instantiation. +(Note, that this use was known before PMD 5.1.0 as UseSingleton).
+ public class MaybeAUtility {
+ public static void foo() {}
+ public static void bar() {}
+ }
+Alternative rule: java:S1118
+]]>Java 5 introduced the varargs parameter declaration for methods and constructors. This syntactic +sugar provides flexibility for users of these methods and constructors, allowing them to avoid +having to deal with the creation of an array.
+Byte arrays in any method and String arrays in public static void main(String[])
methods are ignored.
public class Foo {
+ public void foo(String s, Object[] args) {
+ // Do something here...
+ }
+
+ public void bar(String s, Object... args) {
+ // Ahh, varargs tastes much better...
+ }
+ }
+]]>An operation on an immutable object will not change the object itself since the result of the operation is a new object. +Therefore, ignoring the result of such an operation is likely a mistake. The operation can probably be removed.
+This rule recognizes the types String
, BigDecimal
, BigInteger
or any type from java.time.*
as immutable.
import java.math.*;
+
+ class Test {
+ void method1() {
+ BigDecimal bd=new BigDecimal(10);
+ bd.add(new BigDecimal(5)); // this will trigger the rule
+ }
+ void method2() {
+ BigDecimal bd=new BigDecimal(10);
+ bd = bd.add(new BigDecimal(5)); // this won't trigger the rule
+ }
+ }
+]]>The overriding method merely calls the same method defined in a superclass.
+ public void foo(String bar) {
+ super.foo(bar); // why bother overriding?
+ }
+
+ public String foo() {
+ return super.foo(); // why bother overriding?
+ }
+
+ @Id
+ public Long getId() {
+ return super.getId(); // OK if 'ignoreAnnotations' is false, which is the default behavior
+ }
+Alternative rule: java:S1185
+]]>Parenthesized expressions are used to override the default operator precedence + rules. Parentheses whose removal would not change the relative nesting of operators + are unnecessary, because they don't change the semantics of the enclosing expression.
+Some parentheses that strictly speaking are unnecessary, may still be considered useful for readability. This rule allows to ignore violations on two kinds of unnecessary parentheses:
+ (a == null) != (b == null)
+ a == null != (b == null)
The parentheses on the right are required, and the parentheses on the left are just more visually pleasing. Unset the property ignoreBalancing
to report them. public class Foo {
+ {
+ int n = 0;
+ n = (n); // here
+ n = (n * 2) * 3; // and here
+ n = n * (2 * 3); // and here
+ }
+ }
+Alternative rule: java:S1110
+]]>Reports qualified this usages in the same class.
+ public class Foo {
+ final Foo otherFoo = Foo.this; // use "this" directly
+
+ public void doSomething() {
+ final Foo anotherFoo = Foo.this; // use "this" directly
+ }
+
+ private ActionListener returnListener() {
+ return new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ doSomethingWithQualifiedThis(Foo.this); // This is fine
+ }
+ };
+ }
+
+ private class Foo3 {
+ final Foo myFoo = Foo.this; // This is fine
+ }
+
+ private class Foo2 {
+ final Foo2 myFoo2 = Foo2.this; // Use "this" direclty
+ }
+ }
+]]>No need to call String.valueOf to append to a string; just use the valueOf() argument directly.
+ public String convert(int i) {
+ String s;
+ s = "a" + String.valueOf(i); // not required
+ s = "a" + i; // preferred approach
+ return s;
+ }
+Alternative rule: java:S1153
+]]>do {} while (true);
requires reading the end of the statement before it is
+apparent that it loops forever, whereas while (true) {}
is easier to understand.
do {} while (false);
is redundant, and if an inner variable scope is required,
+a block {}
is sufficient.
while (false) {}
will never execute the block and can be removed in its entirety.
public class Example {
+ {
+ while (true) { } // allowed
+ while (false) { } // disallowed
+ do { } while (true); // disallowed
+ do { } while (false); // disallowed
+ do { } while (false | false); // disallowed
+ do { } while (false || false); // disallowed
+ }
+ }
+]]>Let's take a simple example: assume we have a Factory class that must be always declared final. +We'd like to report a violation each time a declaration of Factory is not declared final. Consider the following class:
+
+import io.factories.Factory;
+
+public class a {
+ Factory f1;
+
+ void myMethod() {
+ Factory f2;
+ int a;
+ }
+}
+
+The following expression does the magic we need:
+
+//(FieldDeclaration|LocalVariableDeclaration)[
+ not (pmd-java:modifiers() = 'final')
+ ]/ClassType[pmd-java:typeIs('io.factories.Factory')]
+
+See the XPath rule tutorial for more information.
+Tip: use the PMD Designer application to create the XPath expressions.
+]]>Alternative " + (alternatives.size() == 1 ? "rule" : "rules") + ": ") + alternatives.eachWithIndex { alt, index -> + if (index > 0) alternativesHtml.append(", ") + def internalLink = "./coding_rules?rule_key=${URLEncoder.encode(alt.key, 'UTF-8')}&open=${URLEncoder.encode(alt.key, 'UTF-8')}" + alternativesHtml.append("${alt.key}") + } + alternativesHtml.append("
") + htmlContent += "\n" + alternativesHtml.toString() + } + } + return htmlContent +} + +def appendExternalInfoLink(String htmlContent, String externalInfoUrl) { + if (externalInfoUrl) { + def linkText = "Full documentation" + htmlContent += "\n" + } + return htmlContent +} + +def writeDescription(xml, Map ruleData, String language) { + def descContent = formatDescription(ruleData, language) + boolean usedFallback = false + if (!descContent || descContent.trim().isEmpty()) { + descContent = MarkdownToHtmlConverter.convertToHtml("THIS SHOULD NOT HAPPEN") + usedFallback = true + } + xml.description { + xml.mkp.yieldUnescaped("") + } + return usedFallback +} + +def addAlternativeTagIfAny(xml, String language, String ruleName) { + def ruleAlternativesForLanguage = language == "Java" ? javaRuleAlternatives : kotlinRuleAlternatives + if (ruleAlternativesForLanguage && ruleAlternativesForLanguage.containsKey(ruleName)) { + xml.tag("has-sonar-alternative") + } +} + +def addParam(xml, String keyName, String descText, String defaultVal, String typeToken) { + xml.param { + key(keyName) + description { + xml.mkp.yieldUnescaped("") + } + // Always emit an explicit empty default when the default is missing + def effectiveDefault = defaultVal + if (effectiveDefault == null) { + effectiveDefault = "" + } + if (effectiveDefault != null) defaultValue(effectiveDefault) + if (typeToken) type(typeToken) + } +} + +def addXmlDefinedRuleParams(xml, Map ruleData, Set existingParamKeys) { + ruleData.properties.findAll { prop -> + prop.name && prop.description + }.each { prop -> + String typeToken = null + if (prop.type) { + def t = prop.type.toUpperCase() + if (t.startsWith("LIST[") || t.contains("REGEX") || t == "REGULAR_EXPRESSION") { + typeToken = "STRING" + } else { + typeToken = t + } + } + addParam(xml, prop.name, prop.description, prop.value, typeToken) + existingParamKeys.add(prop.name) + } +} + +// --- Helpers for addClassDefinedRuleParams --- +def getRulePropertiesForClass(Map rulePropertiesMap, String ruleClass) { + rulePropertiesMap.get(ruleClass) +} + +def getUnwrappedType(propInfo) { + def propType = propInfo.type + try { + return propInfo.getWrappedType() + } catch (MissingMethodException ignore) { + return propType + } +} + +def shouldLogProperty(String propName) { + !(propName == "violationSuppressRegex" || propName == "violationSuppressXPath") +} + +def handleSuppressionSpecialCases(xml, propInfo) { + if (propInfo.name == "violationSuppressXPath") { + // Skip adding this parameter as it's too complex/error-prone for users + return true + } + if (propInfo.name == "violationSuppressRegex") { + // Do not emit this parameter here. It will be added later by addSuppressionParamIfNeeded + // only when the rule message contains variable placeholders. This keeps + // keep the suppression regex description centralized and ensure the param + // is only present when appropriate. + return true + } + return false +} + + +def getAcceptedValues(propInfo) { + try { + return (propInfo.getAcceptedValues() ?: []) as List + } catch (MissingMethodException ignore) { + return [] + } catch (MissingPropertyException ignore) { + return [] + } +} + +def isMultiple(propInfo) { + try { + return propInfo.isMultiple() + } catch (MissingMethodException ignore) { + return false + } +} + +def computeBaseDescription(propInfo, List accepted, boolean multiple) { + RuleParamFormatter.buildDescription( + null, + propInfo.description, + accepted, + multiple + ) +} + +def determineTypeToken(List accepted, boolean multiple, String unwrappedType) { + if (accepted && !accepted.isEmpty()) { + return RuleParamFormatter.buildSelectTypeToken(accepted, multiple) + } + if (unwrappedType in ["Integer", "Long", "Short", "Byte", "BigInteger"]) { + return "INTEGER" + } + if (unwrappedType in ["Double", "Float", "BigDecimal"]) { + return "FLOAT" + } + if (unwrappedType?.equalsIgnoreCase("Boolean")) { + return "BOOLEAN" + } + if (unwrappedType?.equalsIgnoreCase("Pattern")) { + return "STRING" + } + return "STRING" +} + +def computeDefaultValue(propInfo) { + def defVal = (propInfo.defaultValuesAsString) ?: "" + if (defVal == "[]") { + logWarn("wrong $defVal for $propInfo") + } + return defVal +} + +def addParamAndTrack(xml, String name, String desc, String defVal, String typeToken, Set existingParamKeys) { + addParam(xml, name, desc, defVal, typeToken) + existingParamKeys.add(name) +} + +def processStandardProperty(xml, propInfo, Set existingParamKeys) { + def accepted = getAcceptedValues(propInfo) + def multiple = isMultiple(propInfo) + def baseDesc = computeBaseDescription(propInfo, accepted, multiple) + def unwrappedType = getUnwrappedType(propInfo) + def typeToken = determineTypeToken(accepted, multiple, unwrappedType) + def defVal = computeDefaultValue(propInfo) + addParamAndTrack(xml, propInfo.name, baseDesc, defVal, typeToken, existingParamKeys) +} + +// Main orchestrator + +def addClassDefinedRuleParams(xml, Map ruleData, String language, Set existingParamKeys) { + def ruleClass = ruleData.class + if (!ruleClass) return + def rulePropertiesMap = language == "Java" ? javaRuleProperties : kotlinRuleProperties + def ruleProperties = getRulePropertiesForClass(rulePropertiesMap, ruleClass) + if (ruleProperties.size()) { + logDebug(" - found ${ruleProperties.size()} properties for rule ${ruleData.name} (${ruleClass})") + ruleProperties.each { propInfo -> + def propType = propInfo.type + def unwrappedType = getUnwrappedType(propInfo) + if (shouldLogProperty(propInfo.name)) { + logDebug("### PROP: ${propInfo.name} TYPE: ${propType} (wrapped: ${unwrappedType})") + } + if (handleSuppressionSpecialCases(xml, propInfo)) { + return + } + processStandardProperty(xml, propInfo, existingParamKeys) + } + } +} + +def addRuleParams(xml, Map ruleData, String language, Set existingParamKeys) { + if (ruleData.class.equals("net.sourceforge.pmd.lang.rule.xpath.XPathRule")) { + addXmlDefinedRuleParams(xml, ruleData, existingParamKeys) + } else { + addClassDefinedRuleParams(xml, ruleData, language, existingParamKeys) + } +} + +def addSuppressionParamIfNeeded(xml, boolean hasVariablePlaceholders, Set existingParamKeys) { + if (hasVariablePlaceholders && !existingParamKeys.contains("violationSuppressRegex")) { + addParam(xml, + "violationSuppressRegex", + "Suppress violations with messages matching a regular expression. WARNING: make sure the regular expression is correct, otherwise analysis will fail with unclear XML validation errors.", + "", + "STRING" + ) + } +} + +def reportEmptyDescriptions(File outputFile, String language) { + def outputXml = new XmlSlurper().parse(outputFile) + def emptyDescriptions = outputXml.rule.findAll { + !it.description.text() || it.description.text().trim().isEmpty() + } + if (emptyDescriptions.size() > 0) { + logWarn("found ${emptyDescriptions.size()} ${language} rules with empty descriptions:") + emptyDescriptions.each { rule -> + logInfo(" - ${rule.key.text()}") + } + } else { + logInfo("all ${language} rules have descriptions") + } +} + +def handleRenamedRules(String language, int renamedRules, List rulesWithDeprecatedAndRef) { + logWarn("renamed ${renamedRules} ${language} rules with deprecated=true and ref attribute:") + rulesWithDeprecatedAndRef.each { rule -> + logInfo(" - ${rule.name} (ref: ${rule.ref})") + } + def renamedRulesData = [ + language: language, + count: renamedRules, + rules: rulesWithDeprecatedAndRef.collect { rule -> [name: rule.name, ref: rule.ref, category: rule.category] } + ] + def jsonBuilder = new JsonBuilder(renamedRulesData) + def renamedRulesFile = new File("scripts/renamed-${language.toLowerCase()}-rules.json") + renamedRulesFile.write(jsonBuilder.toPrettyString()) + logInfo("generated renamed rules information in ${renamedRulesFile.absolutePath}") +} + +def addXPathRuleToJavaFile() { + addXPathRuleToJavaFile(javaOutputFilePath as File) +} + +def addXPathRuleToJavaFile(File outFile) { + logInfo("") + logInfo("adding XPathRule to Java rules XML file...") + logInfo("=" * 30) + try { + def xmlFile = outFile + def xmlContent = xmlFile.text + if (xmlContent.contains("Let's take a simple example: assume we have a Factory class that must be always declared final. +We'd like to report a violation each time a declaration of Factory is not declared final. Consider the following class:
+
+import io.factories.Factory;
+
+public class Foo {
+ Factory f1;
+
+ void myMethod() {
+ Factory f2;
+ int a;
+ }
+}
+
+The following expression does the magic we need:
+
+//(FieldDeclaration|LocalVariableDeclaration)[
+ not (pmd-java:modifiers() = 'final')
+ ]/ClassType[pmd-java:typeIs('io.factories.Factory')]
+
+See the XPath rule tutorial for more information.
+Tip: use the PMD Designer application to create the XPath expressions.
+]]>