Affects PMD Version:
6.31+
Observed on 6.34
Rule:
LiteralsFirstInComparisons
Description:
Some constant fields are not considered by the rule.
Code Sample demonstrating the issue:
class DT1 { public static final String Q = "q"; public static final String T = "t"; public static int convert(String type) { if (type.equals(Q)) { // 8 return 1; } else if (type.equals(T)) { // 10 return 2; } else { return 3; } } } class DT2 { public static final String Q = "q"; public static final String T = "t"; public static int convert(String type) { if (Q.equals(type)) { // 23 return 1; } else if (type.equals(T)) { // 25 return 2; } else { return 3; } } } class DT3 { public static int convert(String type) { if (type.equals("q")) { // 35 return 1; } else if (type.equals("t")) { // 37 return 2; } else { return 3; } } }
Line 23 has fixed violation from line 8.
Lines 35 and 37 use literals (and rule works fine for them).
Expected outcome:
For the code above I'd also expect violations reported for lines 10 and 25.
Running PMD through:
Found with maven, and here is from CLI:
$ run.sh pmd -R category/java/bestpractices.xml/LiteralsFirstInComparisons -f text -d src/main/java
which results in only
Apr 27, 2021 9:15:32 PM net.sourceforge.pmd.PMD encourageToUseIncrementalAnalysis
WARNING: This analysis could be faster, please consider using Incremental Analysis: https://pmd.github.io/pmd-6.34.0/pmd_userdocs_incremental_analysis.html
.../DTs.java:8: LiteralsFirstInComparisons: Position literals first in String comparisons
.../DTs.java:35: LiteralsFirstInComparisons: Position literals first in String comparisons
.../DTs.java:37: LiteralsFirstInComparisons: Position literals first in String comparisons
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4