forked from jborgers/PMD-jPinpoint-rules
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjpinpoint-java-rules.xml
More file actions
7521 lines (7115 loc) · 386 KB
/
jpinpoint-java-rules.xml
File metadata and controls
7521 lines (7115 loc) · 386 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?xml version="1.0" encoding="UTF-8"?>
<ruleset name="jpinpoint-java-rules"
xmlns="http://pmd.sourceforge.net/ruleset/2.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0 http://pmd.sourceforge.net/ruleset_2_0_0.xsd">
<description>
jPinpoint rules for responsible Java coding, sponsored by Rabobank. Uses PMD-7.
</description>
<!-- IMPORTANT NOTICE: The content of this file is generated. Do not edit this file directly since changes may be lost when this file is regenerated! -->
<!-- BEGIN Included file 'common.xml' -->
<rule name="AvoidCDIReferenceLeak"
language="java"
message="Explicit CDI references need to be destroyed otherwise they leak."
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule"
externalInfoUrl="https://github.com/jborgers/PMD-jPinpoint-rules/tree/pmd7/docs/JavaCodePerformance.md#pml05">
<description>Problem: A proxy object is created by Contexts and Dependency Injection (CDI) for explicit references, they are not de-referenced implicitly and become a memory leak.
Solution: Destroy the reference explicitly.
(jpinpoint-rules)</description>
<priority>1</priority>
<properties>
<property name="tags" value="jpinpoint-rule,memory,performance,sustainability-low" type="String" description="classification"/>
<property name="xpath">
<value><![CDATA[
//MethodCall[@MethodName='select']/MethodCall[@MethodName='current']/TypeExpression/ClassType[@SimpleName='CDI'
and not
(ancestor::MethodDeclaration//TryStatement/FinallyClause
//MethodCall[@MethodName='destroy'][ArgumentList/VariableAccess[@Name=ancestor::
MethodDeclaration//(VariableDeclarator|AssignmentExpression)[.//MethodCall[@MethodName='current']/TypeExpression/ClassType[@SimpleName='CDI']]/(VariableId|VariableAccess)/@Name]]
[MethodCall[@MethodName='current']/TypeExpression/ClassType[@SimpleName='CDI']])
]
]]></value>
</property>
</properties>
<example>
<![CDATA[
public class CDIStuff {
private void bad() {
MyClass o = CDI.current().select(MyClass.class).get();
o.doStuff();
// bad - missing destroy in finally
}
private void good() {
MyClass o = CDI.current().select(MyClass.class).get();
try {
o.doStuff();
} finally {
CDI.current().destroy(o); // good - destroy properly
}
}
}
]]>
</example>
</rule>
<rule name="AvoidCalendar"
language="java"
message="A Calendar is inefficient in memory usage."
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule"
externalInfoUrl="https://github.com/jborgers/PMD-jPinpoint-rules/tree/pmd7/docs/JavaCodePerformance.md#imu01">
<description>Problem: A Calendar is a heavyweight object and expensive to create.
Solution: Use Date, Java 8+ java.time.[Local/Zoned]DateTime.
(jpinpoint-rules)</description>
<priority>3</priority>
<properties>
<property name="xpath">
<value><![CDATA[
//ClassType[pmd-java:typeIs('java.util.Calendar')]
]]></value>
</property>
<property name="tags" value="jpinpoint-rule,memory,performance,sustainability-medium" type="String" description="classification"/>
</properties>
<example>
<![CDATA[
public class CalendarStuff {
Calendar field1; // bad
private Calendar bad1() {
return Calendar.getInstance();
}
private Date good1a() {
return new Date(); // now
}
private LocalDateTime good1b() {
return LocalDateTime.now();
}
}
]]>
</example>
</rule>
<rule name="AvoidConstantsInInterface"
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule"
language="java" message="Interface defines constants. It may expose implementation details."
externalInfoUrl="https://github.com/jborgers/PMD-jPinpoint-rules/tree/pmd7/docs/JavaCodePerformance.md#voedos04">
<description>Interface defines constants. Problem: Possibly exposes implementation details.
Solution: Make it a Class which cannot be instantiated, or an Enum. Use static imports.
(jpinpoint-rules)</description>
<priority>3</priority>
<properties>
<property name="tags" value="jpinpoint-rule,bad-practice" type="String" description="classification"/>
<property name="xpath">
<value><![CDATA[
//ClassDeclaration[@Interface=true()]/ClassBody/FieldDeclaration
]]></value>
</property>
</properties>
<example>
<![CDATA[
public interface AnimalConsts {
public static final Dog DOG = new Dog(); //bad
}
public class AnimalUtil {
private AnimalUtil() {}
public static final Dog DOG = new Dog(); // good
}
public enum Animal {
DOG // good
}
]]>
</example>
</rule>
<rule name="AvoidDecimalAndChoiceFormatAsField"
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule"
language="java"
message="Avoid using DecimalFormat or ChoiceFormat as field since it is thread-unsafe."
externalInfoUrl="https://github.com/jborgers/PMD-jPinpoint-rules/tree/pmd7/docs/JavaCodePerformance.md#idtf01">
<description>Problem: java.text.NumberFormat: DecimalFormat and ChoiceFormat are thread-unsafe.
Solution: usual solution is to create a new local one when needed in a method.
(jpinpoint-rules)
(jpinpoint-rules)</description>
<priority>1</priority>
<properties>
<property name="tags" value="jpinpoint-rule,multi-threading" type="String" description="classification"/>
<property name="xpath">
<value><![CDATA[
//FieldDeclaration/ClassType[pmd-java:typeIs('java.text.NumberFormat')]
]]></value>
</property>
</properties>
<example>
<![CDATA[
public class Foo {
public static final DecimalFormat NUMBER_FORMAT = new DecimalFormat("###.###"); // bad
public void bar() {
NumberFormat format = new DecimalFormat("###.###"); // good
}
}
]]>
</example>
</rule>
<rule name="AvoidDuplicateAssignmentsInCases"
message="Avoid duplicate assignments in different switch cases"
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule" language="java"
externalInfoUrl="https://github.com/jborgers/PMD-jPinpoint-rules/tree/pmd7/docs/JavaCodeQuality.md#SSC01">
<description>
Problem: Potential bug: expected to have different assignments in different cases.
Solution: assign different values in different cases, common assignments should be taken out of the switch.
(jpinpoint-rules)</description>
<priority>2</priority>
<properties>
<property name="tags" value="jpinpoint-rule,suspicious" type="String" description="classification"/>
<property name="xpath">
<value>
<![CDATA[
(:-- assigned to same var in a previous switch case --:)
//SwitchStatement//SwitchFallthroughBranch/ExpressionStatement[AssignmentExpression[not(pmd-java:typeIs('boolean'))]/VariableAccess[1]/@Name=
../preceding-sibling::SwitchFallthroughBranch//preceding-sibling::ExpressionStatement/AssignmentExpression/VariableAccess[1]/@Name
and (
(:-- assigning same var --:)
AssignmentExpression/VariableAccess[2]/@Name=
../preceding-sibling::SwitchFallthroughBranch//preceding-sibling::ExpressionStatement/AssignmentExpression/VariableAccess[2]/@Name
or
(:-- assigning same literal --:)
AssignmentExpression/(StringLiteral|NumericLiteral)/@Image =
../preceding-sibling::SwitchFallthroughBranch//preceding-sibling::ExpressionStatement/AssignmentExpression/(StringLiteral|NumericLiteral)/@Image
or
(:-- assigning constructor with same argument--:)
AssignmentExpression/ConstructorCall/ArgumentList[@Size=1]/StringLiteral/@ConstValue =
../preceding-sibling::SwitchFallthroughBranch//preceding-sibling::ExpressionStatement/AssignmentExpression/ConstructorCall/ArgumentList[@Size=1]/StringLiteral/@ConstValue
or
(:-- assigning same argumentless method possibly on a field of a type --:)
AssignmentExpression/MethodCall[ArgumentList[@Size=0]]/concat(@MethodName, .//FieldAccess/@Name, .//FieldAccess//ClassType/@SimpleName) =
../preceding-sibling::SwitchFallthroughBranch//preceding-sibling::ExpressionStatement/AssignmentExpression/MethodCall[ArgumentList[@Size=0]]/concat(@MethodName, .//FieldAccess/@Name, .//FieldAccess//ClassType/@SimpleName)
)
(:--default case allowed to have duplicates --:)
and not (preceding-sibling::SwitchLabel[@Default=true()])]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
switch (type) {
case "One":
xmlNsExtValue = "same";
schemaLocation = 1;
startElement = N_INITN;
extra = new String("alsoSame");
extra = dummy;
extra = toString();
break;
case "Two":
xmlNsValue = LINT008; // good
xmlNsExtValue = "same"; // bad
schemaLocation = 1; // bad
startElement = Y_INITN; // good
extra = new String("alsoSame"); // bad
break;
default:
throw new IllegalArgumentException("Type " + type + " is not supported.");
}
]]>
</example>
</rule>
<rule name="AvoidExposingMutableRecordState"
language="java"
message="Avoid exposing mutable state of the record. Use copyOf in the (compact) constructor."
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule"
externalInfoUrl="https://github.com/jborgers/PMD-jPinpoint-rules/tree/pmd7/docs/JavaCodePerformance.md#voedos06">
<description>Problem: Internal state can be modified from outside the record, through the implicit accessor method or by the caller of the constructor. Risk of thread-unsafety.
Solution: Use the record compact constructor to defensively copy the (possibly) mutable object such as a List, Set or Map, e.g. with List.copyOf(). Make sure
to avoid NullPointerExceptions for null values in List.copyOf() methods. Beware that contained objects in collections can itself be mutable.
(jpinpoint-rules)</description>
<priority>3</priority>
<properties>
<property name="tags" value="jpinpoint-rule,multi-threading" type="String" description="classification"/>
<property name="xpath">
<value><![CDATA[
//RecordDeclaration//RecordComponent/ClassType[(pmd-java:typeIs('java.util.Collection') or pmd-java:typeIs('java.util.Map'))
and not(../VariableId/@Name = ancestor::RecordDeclaration/RecordBody/(CompactConstructorDeclaration|ConstructorDeclaration)
//AssignmentExpression[(VariableAccess|FieldAccess)/@Name = .//MethodCall[contains(lower-case(@MethodName), 'copyof')]
/ArgumentList//(VariableAccess|FieldAccess)/@Name]/(VariableAccess|FieldAccess)/@Name)
]/..
]]></value>
</property>
</properties>
<example>
<![CDATA[
record BadRecord(String name, List<String> list) {
}
record GoodRecord(String name, List<String> list) {
public GoodRecord {
list = list != null ? List.copyOf(list) : List.of();
}
}
]]>
</example>
</rule>
<rule name="AvoidImplicitlyRecompilingRegex" class="net.sourceforge.pmd.lang.rule.xpath.XPathRule" language="java" message="String regex method, Pattern.matches or FileSystem.getPathMatcher is used.
Implicitly compiles a regex pattern, can be expensive."
externalInfoUrl="https://github.com/jborgers/PMD-jPinpoint-rules/tree/pmd7/docs/JavaCodePerformance.md#ireu01">
<description>A regular expression is compiled implicitly on every invocation. Problem: this can be expensive, depending on the length of the regular expression.
Solution: Compile the regex pattern only once and assign it to a private static final Pattern field. java.util.Pattern objects are thread-safe, so they can be shared among threads.
(jpinpoint-rules)</description>
<priority>2</priority>
<properties>
<property name="tags" value="cpu,jpinpoint-rule,performance,sustainability-medium" type="String" description="classification"/>
<property name="xpath">
<value><![CDATA[
(:- method calls for non-short regex literals and used fields defined with non-short regex literal, or not defined as field -:)
//MethodDeclaration//MethodCall[pmd-java:matchesSig('java.lang.String#replaceAll(java.lang.String,java.lang.String)')
or pmd-java:matchesSig('java.lang.String#replaceFirst(java.lang.String,java.lang.String)')
or pmd-java:matchesSig('java.util.regex.Pattern#matches(java.lang.String,java.lang.CharSequence)')
or pmd-java:matchesSig('java.lang.String#split(java.lang.String)')
or pmd-java:matchesSig('java.lang.String#matches(java.lang.String)')
or pmd-java:matchesSig('java.nio.file.FileSystem#getPathMatcher(java.lang.String)')
]
/ArgumentList/*[1][(self::StringLiteral and string-length(@Image) > 5 and
(matches(@Image, '[\.\$\|\(\)\[\]\{\}\^\?\*\+\\]+')))
or
self::VariableAccess and @Name=ancestor::ClassBody[1]/FieldDeclaration/VariableDeclarator[StringLiteral[string-length(@Image) > 5 and
(matches(@Image, '[\.\$\|\(\)\[\]\{\}\^\?\*\+\\]+'))] or not(StringLiteral)]/VariableId/@Name]
]]></value>
</property>
</properties>
<example>
<![CDATA[
String bad_replaceInnerLineBreakBySpace() {
return text.replaceAll("([^\\.\\n])\\n", "$1 "); // bad
}
private static final Pattern INNER_LINE_BREAK_PATTERN = Pattern.compile("([^\\.\\n])\\n"); // good
String good_replaceInnerLineBreakBySpace() {
return INNER_LINE_BREAK_PATTERN.matcher(text).replaceAll("$1 "); // good
}
]]>
</example>
</rule>
<rule name="AvoidInMemoryStreamingDefaultConstructor"
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule"
language="java"
message="The default capacity or smaller is used for ByteArrayOutputStream or StringWriter, it usually needs expensive expansions."
externalInfoUrl="https://github.com/jborgers/PMD-jPinpoint-rules/tree/pmd7/docs/JavaCodePerformance.md#isio01">
<description>Problem: The default constructor of ByteArrayOutputStream creates a 32 bytes initial capacity and for StringWriter 16 chars. Problem: Such a small buffer as capacity usually needs several expensive expansions.
Solution: Pre-size the ByteArrayOutputStream or StringWriter with an initial capacity such that an expansion is not needed in most cases, typically much larger than 32, for instance 4096.
(jpinpoint-rules)</description>
<priority>2</priority>
<properties>
<property name="tags" value="cpu,jpinpoint-rule,performance,sustainability-medium" type="String" description="classification"/>
<property name="xpath">
<value><![CDATA[
//ConstructorCall[pmd-java:matchesSig('java.io.ByteArrayOutputStream#new()') or pmd-java:matchesSig('java.io.StringWriter#new()')
or
((pmd-java:matchesSig('java.io.ByteArrayOutputStream#new(int)') and (ArgumentList/NumericLiteral/@ValueAsInt <=32
or ArgumentList/VariableAccess/@Name = ancestor::ClassBody[1]/FieldDeclaration/VariableDeclarator[NumericLiteral/@ValueAsInt <= 32]/VariableId/@Name))
or (pmd-java:matchesSig('java.io.StringWriter#new(int)') and (ArgumentList/NumericLiteral/@ValueAsInt <=16
or ArgumentList/VariableAccess/@Name = ancestor::ClassBody[1]/FieldDeclaration/VariableDeclarator[NumericLiteral/@ValueAsInt <= 16]/VariableId/@Name))
)
]
]]></value>
</property>
</properties>
<example>
<![CDATA[
class Bad {
public static void bad() {
ByteArrayOutputStream baos = new ByteArrayOutputStream(); //bad
StringWriter sw = new StringWriter(); //bad
baos = new ByteArrayOutputStream(32); //bad - not larger than default
}
}
class Good {
public static void good() {
ByteArrayOutputStream baos = new ByteArrayOutputStream(8192); // 8 kiB
StringWriter sw = new StringWriter(2048);
}
}
]]>
</example>
</rule>
<rule name="AvoidInfiniteRecursion"
language="java"
message="Avoid recursive calls without a proper stop condition."
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule"
externalInfoUrl="https://github.com/jborgers/PMD-jPinpoint-rules/tree/pmd7/docs/JavaCodePerformance.md#ipf01">
<description>Problem: If a method calls itself (recursion), and it doesn't have a proper and guaranteed stop condition, it may become an infinite loop and result in an OutOfMemoryError or StackOverflowError, and high CPU usage.
Solution: Limit the number of recursive calls: use a counter to count up-to or down-from a maximum number of calls, for every recursive call, and stop when the maximum is reached. This maximum should not be a large number.
Or better yet, rewrite into iterations for better performance and avoiding errors.
(jpinpoint-rules)</description>
<priority>1</priority>
<properties>
<property name="xpath">
<value><![CDATA[
//MethodDeclaration[not(.//IfStatement[
((.//UnaryExpression[@Operator=('++', '--')]|.//InfixExpression[@Operator=('+', '-')]/NumericLiteral[@ValueAsInt=1]|.//AssignmentExpression[@Operator=('+=', '-=')]/NumericLiteral[@ValueAsInt=1])
or .//MethodCall[contains(@MethodName,'crement')]/VariableAccess[pmd-java:typeIs('java.lang.Number')])
and .//InfixExpression[@Operator=('>', '>=','<', '<=')]
(: same method name :)
])]//MethodCall[@MethodName = ancestor::MethodDeclaration/@Name]
(: only called on implicit or explicit this :)
[(ArgumentList and count(*) = 1) or (ArgumentList and ThisExpression and count(*) = 2)]
(: if this has a classType, it must be the same as the first containing class :)
[not(exists(ThisExpression/ClassType)) or ThisExpression/ClassType/@SimpleName = ancestor::ClassDeclaration[1]/@SimpleName]
(: only if the number of parameters match: not an overloaded method with difference in numbers :)
[ArgumentList/@Size = ancestor::MethodDeclaration/FormalParameters/@Size]
(: not if any parameter is used in the call in another position :)
[not((ArgumentList/*[self::VariableAccess and ((position() != index-of(ancestor::MethodDeclaration/FormalParameters/FormalParameter/VariableId/@Name, concat('', @Name))))]))]
(: we check the first 3 arguments on type, which is complicated :)
(: if the 1st parameter (if it exists) :)
(: its name equals the name of the 1st argument of the called method :)
[concat(ArgumentList/*[1]/@Name, '') = ancestor::MethodDeclaration/FormalParameters/FormalParameter[1]/VariableId/@Name
or ArgumentList/MethodCall/TypeExpression/ClassType/@SimpleName = ancestor::MethodDeclaration/FormalParameters/FormalParameter[1]/ClassType/@SimpleName
or ancestor::MethodDeclaration/FormalParameters[@Size = 0 or FormalParameter[1][(
(: or its classType is equal to the local var classtype :)
(ClassType/@SimpleName|PrimitiveType/@Kind) = ancestor::MethodDeclaration//LocalVariableDeclaration[
(: which name equals to the name of the 1st argument of the method call :)
.//VariableId/@Name = ancestor::MethodDeclaration//MethodCall[@MethodName = ancestor::MethodDeclaration/@Name]/ArgumentList/VariableAccess[1]/@Name
][
(: and which classType is equal to the classtype of the first parameter :)
((ClassType/@SimpleName|PrimitiveType/@Kind) = ancestor::MethodDeclaration/FormalParameters/FormalParameter[1]/(ClassType/@SimpleName|PrimitiveType/@Kind))
]/(ClassType/@SimpleName|PrimitiveType/@Kind)
or
(: or its classType is equal to the field classtype :)
(ClassType/@SimpleName|PrimitiveType/@Kind) = ancestor::ClassBody[1]/FieldDeclaration[
(: which name equals to the name of the 1st argument of the method call :)
.//VariableId/@Name = ..//MethodDeclaration//MethodCall[@MethodName = ancestor::MethodDeclaration/@Name]/ArgumentList/VariableAccess[1]/@Name
][
(: and which classType is equal to the classtype of the first parameter :)
((ClassType/@SimpleName|PrimitiveType/@Kind) = ..//MethodDeclaration/FormalParameters/FormalParameter[1]/(ClassType/@SimpleName|PrimitiveType/@Kind))
]/(ClassType/@SimpleName|PrimitiveType/@Kind))
]]]
(: if the 2nd parameter (if it exists) :)
[concat(ArgumentList/*[2]/@Name, '') = ancestor::MethodDeclaration/FormalParameters/FormalParameter[2]/VariableId/@Name
or ancestor::MethodDeclaration/FormalParameters[@Size <= 1 or FormalParameter[2][(
(: or its classType is equal to the local var classtype :)
(ClassType/@SimpleName|PrimitiveType/@Kind) = (ancestor::MethodDeclaration//LocalVariableDeclaration|ancestor::ClassBody[1]/FieldDeclaration)[
(: which name equals to the name of the 2nd argument of the method call :)
.//VariableId/@Name = ancestor::MethodDeclaration//MethodCall[@MethodName = ancestor::MethodDeclaration/@Name]/ArgumentList/VariableAccess[2]/@Name][
(: and which classType is equal to the classtype of the 2nd parameter :)
((ClassType/@SimpleName|PrimitiveType/@Kind) = ancestor::MethodDeclaration/FormalParameters/FormalParameter[2]/(ClassType/@SimpleName|PrimitiveType/@Kind))
]/(ClassType/@SimpleName|PrimitiveType/@Kind)
or
(: or its classType is equal to the field classtype :)
(ClassType/@SimpleName|PrimitiveType/@Kind) = ancestor::ClassBody[1]/FieldDeclaration[
(: which name equals to the name of the 2nd argument of the method call :)
.//VariableId/@Name = ..//MethodDeclaration//MethodCall[@MethodName = ancestor::MethodDeclaration/@Name]/ArgumentList/VariableAccess[2]/@Name
][
(: and which classType is equal to the classtype of the 2nd parameter :)
((ClassType/@SimpleName|PrimitiveType/@Kind) = ..//MethodDeclaration/FormalParameters/FormalParameter[2]/(ClassType/@SimpleName|PrimitiveType/@Kind))
]/(ClassType/@SimpleName|PrimitiveType/@Kind))
]]]
(: if the 3rd parameter (if it exists) :)
[concat(ArgumentList/*[3]/@Name, '') = ancestor::MethodDeclaration/FormalParameters/FormalParameter[3]/VariableId/@Name
or ancestor::MethodDeclaration/FormalParameters[@Size <= 2 or FormalParameter[3][(
(: or its classType is equal to the local var classtype :)
(ClassType/@SimpleName|PrimitiveType/@Kind) = (ancestor::MethodDeclaration//LocalVariableDeclaration|ancestor::ClassBody[1]/FieldDeclaration)[
(: which name equals to the name of the 3rd argument of the method call :)
.//VariableId/@Name = ancestor::MethodDeclaration//MethodCall[@MethodName = ancestor::MethodDeclaration/@Name]/ArgumentList/VariableAccess[3]/@Name][
(: and which classType is equal to the classtype of the 3rd parameter :)
((ClassType/@SimpleName|PrimitiveType/@Kind) = ancestor::MethodDeclaration/FormalParameters/FormalParameter[3]/(ClassType/@SimpleName|PrimitiveType/@Kind))
]/(ClassType/@SimpleName|PrimitiveType/@Kind)
or
(: or its classType is equal to the field classtype :)
(ClassType/@SimpleName|PrimitiveType/@Kind) = ancestor::ClassBody[1]/FieldDeclaration[
(: which name equals to the name of the 3rd argument of the method call :)
.//VariableId/@Name = ..//MethodDeclaration//MethodCall[@MethodName = ancestor::MethodDeclaration/@Name]/ArgumentList/VariableAccess[3]/@Name
][
(: and which classType is equal to the classtype of the 3rd parameter :)
((ClassType/@SimpleName|PrimitiveType/@Kind) = ..//MethodDeclaration/FormalParameters/FormalParameter[3]/(ClassType/@SimpleName|PrimitiveType/@Kind))
]/(ClassType/@SimpleName|PrimitiveType/@Kind))
]]]
]]></value>
</property>
<property name="tags" value="cpu,jpinpoint-rule,memory,performance,pitfall,sustainability-medium" type="String" description="classification"/>
</properties>
<example>
<![CDATA[
class InfiniteRecursionBad {
private void foo() {
boolean success = tryRemoteCall();
if (!success) {
delay(10, MILLISECONDS);
foo(); // bad
}
}
}
class FiniteRecursionGood {
private static final int MAX_ATTEMPTS = 5;
private void foo(int attemptsLeft) {
boolean success = tryRemoteCall();
if (!success && attemptsLeft > 0 ) {
delay(10, MILLISECONDS);
foo(--attemptsLeft);
}
}
}
class IterationsBetter {
private static final int MAX_ATTEMPTS = 5;
private void foo() {
int attempt = 0;
boolean success = false;
while (!success && attempt++ < MAX_ATTEMPTS) {
success = tryRemoteCall();
if (!success) {
delay(10, MILLISECONDS);
}
}
}
}
]]>
</example>
</rule>
<rule name="AvoidLoadingAllFromFile"
language="java"
message="Files.readAll methods and similar APIs load all bytes into memory: a risk of memory problems."
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule"
externalInfoUrl="https://github.com/jborgers/PMD-jPinpoint-rules/tree/pmd7/docs/JavaCodePerformance.md#isio03">
<description>
Problem: APIs like Files.readAllBytes, Files.readAllLines, Files.readString,
InputStream.readAllBytes, IOUtils.toByteArray, ByteArrayInputStream,
ByteArrayOutputStream.toByteArray, and ResizableByteArrayOutputStream.toByteArray
load entire content into heap memory. This risks OutOfMemoryError, long GC pauses,
and slow responses when processing large files.
Solution: Use streaming APIs end-to-end, do not buffer whole files in memory.
Note: Not a problem for small files. In that case use e.g.:
@SuppressWarnings("PMD.AvoidLoadingAllFromFile") // only small files: max 1 kB.
(jpinpoint-rules)
(jpinpoint-rules)</description>
<priority>2</priority>
<properties>
<property name="tags" value="jpinpoint-rule,memory,performance,sustainability-medium" type="String" description="classification"/>
<property name="xpath">
<value><![CDATA[
//MethodCall[
(TypeExpression[pmd-java:typeIs('java.nio.file.Files')] and @MethodName=('readAllBytes', 'readAllLines', 'readString'))
or pmd-java:matchesSig('java.io.InputStream#readAllBytes()')
or (TypeExpression[pmd-java:typeIs('org.apache.commons.io.IOUtils')] and @MethodName='toByteArray')
or (VariableAccess[pmd-java:typeIs('java.io.ByteArrayOutputStream')] and @MethodName='toByteArray')
or (VariableAccess[pmd-java:typeIs('org.springframework.util.ResizableByteArrayOutputStream')] and @MethodName='toByteArray')
]
|
//ConstructorCall[pmd-java:typeIs('java.io.ByteArrayInputStream')]
]]></value>
</property>
</properties>
<example><![CDATA[
class Bad {
void bad(Path path, InputStream in) throws Exception {
byte[] fileBytes = Files.readAllBytes(path); // bad
List<String> fileLines = Files.readAllLines(path); // bad
String s = Files.readString(path); // bad
byte[] full = IOUtils.toByteArray(in); // bad
ByteArrayInputStream bis = new ByteArrayInputStream(full); // bad
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] arr = baos.toByteArray(); // bad
}
}
class Good {
void good(Path path, InputStream in) throws Exception {
try (InputStream s = Files.newInputStream(path)) {
IOUtils.copy(s, System.out); // streaming OK
}
try (BufferedReader reader = Files.newBufferedReader(path)) {
String line = reader.readLine(); // streaming OK
}
}
}
]]>
</example>
</rule>
<rule name="AvoidLombokAnnotationForNonExistentFields"
language="java"
message="Avoid Lombok annotations for fields of a class while the class has no fields."
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule"
externalInfoUrl="">
<description>Problem: Lombok annotations for fields [@Getter, @Setter, @EqualsAndHashCode, @Value, @Data] are of no use and confusing in case the class has no fields.
Solution: Remove the Lombok annotation.
(jpinpoint-rules)</description>
<priority>4</priority>
<properties>
<property name="tags" value="jpinpoint-rule,confusing" type="String" description="classification"/>
<property name="xpath">
<value><![CDATA[
//ClassDeclaration/ModifierList/Annotation
[pmd-java:typeIs('lombok.Getter') or pmd-java:typeIs('lombok.Setter') or pmd-java:typeIs('lombok.Value') or
pmd-java:typeIs('lombok.Data') or pmd-java:typeIs('lombok.EqualsAndHashCode')]
[ancestor::ClassDeclaration[1]/ClassBody[count(FieldDeclaration) = 0]]
]]></value>
</property>
</properties>
<example>
<![CDATA[
@Data // bad
public class BusinessException extends RuntimeException {
// no fields, no methods
}
]]>
</example>
</rule>
<rule name="AvoidMultipleConcatStatements"
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule"
language="java"
message="Multiple statements concatenate to the same String. Use StringBuilder append."
externalInfoUrl="https://github.com/jborgers/PMD-jPinpoint-rules/tree/pmd7/docs/JavaCodePerformance.md#isu02">
<description>Multiple statements concatenate to the same String. Problem: Each statement with one or more +-operators creates a hidden temporary StringBuilder, a char[] and a new String object, which all have to be garbage collected.
Solution: Use StringBuilder.append.
(jpinpoint-rules)</description>
<priority>2</priority>
<properties>
<property name="tags" value="cpu,jpinpoint-rule,performance,sustainability-low" type="String" description="classification"/>
<property name="xpath">
<value><![CDATA[
(: x += y with only one preceding x += v or x = x + w :)
//AssignmentExpression[@Operator='+='][VariableAccess/@Name=ancestor::Block//VariableDeclarator/VariableId[pmd-java:typeIs('java.lang.String')]/@Name]
[(VariableAccess/@Name = ../preceding-sibling::ExpressionStatement/AssignmentExpression[@Operator='+=']/VariableAccess/@Name
or
VariableAccess/@Name = ../preceding-sibling::ExpressionStatement//InfixExpression[@Operator='+']/VariableAccess/@Name)
and not (
VariableAccess/@Name = ../preceding-sibling::ExpressionStatement[2]/AssignmentExpression[@Operator='+=']/VariableAccess/@Name
or
VariableAccess/@Name = ../preceding-sibling::ExpressionStatement[2]//InfixExpression[@Operator='+']/VariableAccess/@Name
)
]
|
(: x = x + y with only one preceding x += v or x = x + w :)
//InfixExpression[@Operator='+'][VariableAccess/@Name=ancestor::AssignmentExpression/VariableAccess/@Name][VariableAccess/@Name=ancestor::Block//VariableDeclarator/VariableId[pmd-java:typeIs('java.lang.String')]/@Name]
[(VariableAccess/@Name = ancestor::ExpressionStatement/preceding-sibling::ExpressionStatement//InfixExpression[@Operator='+']/VariableAccess/@Name
or
VariableAccess/@Name = ancestor::ExpressionStatement/preceding-sibling::ExpressionStatement/AssignmentExpression[@Operator='+=']/VariableAccess/@Name)
and not (
VariableAccess/@Name = ancestor::ExpressionStatement/preceding-sibling::ExpressionStatement[2]/AssignmentExpression[@Operator='+=']/VariableAccess/@Name
or
VariableAccess/@Name = ancestor::ExpressionStatement/preceding-sibling::ExpressionStatement[2]//InfixExpression[@Operator='+']/VariableAccess/@Name
)
]/..
]]></value>
</property>
</properties>
<example>
<![CDATA[
class ConcatsExample {
private String[] values = {"tic", "tac"};
String bad() {
String logStatement = "";
logStatement += values[0];
return logStatement += values[1]; // bad
}
String good() {
StringBuilder logStmtBuilder = new StringBuilder();
return logStmtBuilder.append(values[0]).append(values[1]).toString(); // good
}
}
]]>
</example>
</rule>
<rule name="AvoidMutableLists"
language="java"
message="List is not modified after object construction, make it immutable or unmodifiable"
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule"
externalInfoUrl="https://github.com/jborgers/PMD-jPinpoint-rules/tree/pmd7/docs/JavaCodePerformance.md#pml01">
<description>Problem: A list which is unnecessarily mutable may accidentally be added to and cause a memory leak.
Solution: For the list which is not actually modified, make it impossible to modify after object construction/initialization: use Java 9 List.of, Java 11 List.copyOf, Collections.unmodifiableList or Guava ImmutableList.
(jpinpoint-rules)</description>
<priority>3</priority>
<properties>
<property name="tags" value="jpinpoint-rule,pitfall" type="String" description="classification"/>
<property name="xpath">
<value><![CDATA[
//ClassDeclaration[not(ModifierList/Annotation
[pmd-java:typeIs('lombok.Getter') or pmd-java:typeIs('lombok.Setter') or pmd-java:typeIs('lombok.Value') or
pmd-java:typeIs('lombok.Data')])]
(: a field of type List :)
//FieldDeclaration[//VariableId[pmd-java:typeIs('java.util.List')]]
(: not for field with @Getter and @Setter, it is accessed outside of the class :)
[not(ModifierList/Annotation[pmd-java:typeIs('lombok.Getter') or pmd-java:typeIs('lombok.Setter')])]
(: exclude ConfigurationProperties classes :)
[count(ancestor::ClassDeclaration/ModifierList/Annotation[@SimpleName='ConfigurationProperties']) = 0]
(: exclude when JPA annotated :)
[count(ModifierList/Annotation[@SimpleName=('OneToMany', 'ManyToMany')]) = 0]
//VariableId[
(: with no method defined at that level that uses the field with a modify operation (case field.modOp) :)
not(@Name = ancestor::ClassBody/MethodDeclaration/Block//MethodCall[
starts-with(@MethodName, 'add') or starts-with(@MethodName, 'remove') or
@MethodName = ('set', 'clear', 'replaceAll', 'retainAll')
]/(VariableAccess|FieldAccess)/@Name)
]
[ (: field is initialized with List constructor :)
../ConstructorCall[pmd-java:typeIs('java.util.List')]
or
(: or static block / constructor has field initialized with List allocation :)
ancestor::ClassBody/(Initializer|ConstructorDeclaration)//AssignmentExpression[ConstructorCall[pmd-java:typeIs('java.util.List')]]/(VariableAccess|FieldAccess)[1]/@Name = @Name
or
(: or constructor has a simple assignment to the field, param or literal: no arguments :)
ancestor::ClassBody/ConstructorDeclaration/Block//AssignmentExpression[(VariableAccess|FieldAccess)[2][pmd-java:typeIs('java.util.List')]]/(VariableAccess|FieldAccess)[1]/@Name = @Name
]
]]></value>
</property>
</properties>
<example>
<![CDATA[
public class Bad {
List unmutated = new ArrayList(Arrays.asList("one", "two")); // bad
List mutated = new ArrayList();
private void mutate() {
mutated.add("one");
}
}
public class Good {
List unmutated1 = Collections.unmodifiableList(Arrays.asList("one", "two")); // Java 8
List unmutated2 = List.of("one", "two"); // Java 9+
List mutated = new ArrayList();
private void mutate() {
mutated.add("one");
}
}
]]>
</example>
</rule>
<rule name="AvoidReStreamingEnumValues"
language="java"
message="Avoid re-streaming enum values to find a value by a field."
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule"
externalInfoUrl="https://github.com/jborgers/PMD-jPinpoint-rules/tree/pmd7/docs/JavaCodePerformance.md#iuoc07">
<description>Problem: the time to find element is O(n); n = the number of enum values. This identical processing is executed for every call. Considered problematic when n > 3.
Solution: use a static field-to-enum-value Map. Access time is O(1), provided the hashCode is well-defined.
For one String field, usually toString returns that field. Implement a fromString method to provide the reverse conversion by using the map.
(jpinpoint-rules)</description>
<priority>3</priority>
<properties>
<property name="tags" value="cpu,jpinpoint-rule,performance,sustainability-medium" type="String" description="classification"/>
<property name="xpath">
<value><![CDATA[
//EnumDeclaration/EnumBody[count(EnumConstant) > 3]//MethodDeclaration/Block
//MethodCall[pmd-java:matchesSig('java.util.stream.Stream#findFirst()') or pmd-java:matchesSig('java.util.stream.Stream#findAny()')]
[//MethodCall[pmd-java:matchesSig('java.util.stream.Stream#of(_)') or pmd-java:matchesSig('java.util.Arrays#stream(_)')]
[ArgumentList/MethodCall[pmd-java:matchesSig('_#values()')]]]
]]></value>
</property>
</properties>
<example>
<![CDATA[
// BAD
public enum Fruit {
APPLE("apple"),
ORANGE("orange"),
BANANA("banana"),
KIWI("kiwi");
private final String name;
Fruit(String name) { this.name = name; }
@Override public String toString() { return name; }
public static Optional<Fruit> fromString(String name) {
return Stream.of(values()).filter(v -> v.toString().equals(name)).findAny(); // bad: iterates for every call, O(n) access time
}
}
Usage: `Fruit f = Fruit.fromString("banana");`
// GOOD
public enum Fruit {
APPLE("apple"),
ORANGE("orange"),
BANANA("banana"),
KIWI("kiwi");
private static final Map<String, Fruit> nameToValue =
Stream.of(values()).collect(toMap(Object::toString, v -> v));
private final String name;
Fruit(String name) { this.name = name; }
@Override public String toString() { return name; }
public static Optional<Fruit> fromString(String name) {
return Optional.ofNullable(nameToValue.get(name)); // good, get from Map, O(1) access time
}
} ]]>
</example>
</rule>
<rule name="AvoidRecompilingPatterns"
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule"
language="java"
message="Pattern.compile is used in a method. Compiling a regex pattern can be expensive, make it a static final field."
externalInfoUrl="https://github.com/jborgers/PMD-jPinpoint-rules/tree/pmd7/docs/JavaCodePerformance.md#ireu02">
<description>A regular expression is compiled on every invocation. Problem: this can be expensive, depending on the length of the regular expression.
Solution: Usually a pattern is a literal, not dynamic and can be compiled only once. Assign it to a private static field. java.util.Pattern objects are thread-safe so they can be shared among threads.
(jpinpoint-rules)</description>
<priority>2</priority>
<properties>
<property name="tags" value="cpu,jpinpoint-rule,performance,sustainability-medium" type="String" description="classification"/>
<property name="xpath">
<value><![CDATA[
//MethodDeclaration//MethodCall[pmd-java:matchesSig('java.util.regex.Pattern#compile(java.lang.String)')
and not(.//VariableAccess[@Name = ancestor::MethodDeclaration//FormalParameter/VariableId/@Name])]
]]></value>
</property>
</properties>
<example>
<![CDATA[
class Bad {
public static final String STR_PAT1 = "[A-Z][a-z]+";
public static void bad() {
Pattern p1 = Pattern.compile(STR_PAT1); // bad
Pattern p2 = Pattern.compile("(?=\\p{Lu})"); // bad
boolean b = p1.matcher("Start ").matches();
}
}
class Good {
public static final Pattern PAT1 = Pattern.compile("[A-Z][a-z]+");
public static final Pattern PAT2 = Pattern.compile("(?=\\p{Lu})");
public static void good() {
boolean b = PAT1.matcher("Start ").matches();
}
}
]]>
</example>
</rule>
<rule name="AvoidRecompilingXPathExpression" class="net.sourceforge.pmd.lang.rule.xpath.XPathRule" language="java" message="XPathExpression is created and compiled every time. Beware it is thread-unsafe."
externalInfoUrl="https://github.com/jborgers/PMD-jPinpoint-rules/tree/pmd7/docs/JavaCodePerformance.md#ux02">
<description>XPathExpression is created and compiled on every method call, compiled possibly implicitly by XPath::evaluate.
Problem: Creation of XPath and compilation of XPathExpression takes time. It may slow down your application.
Solution:
1. Avoid XPath usage.
2. Compile the xpath expression as String into a XPathExpression. However, since XPath and XPathExpression classes are thread-unsafe, they are not easily cached. Caching it in a ThreadLocal may be a solution.
(jpinpoint-rules)</description>
<priority>2</priority>
<properties>
<property name="tags" value="cpu,jpinpoint-rule,performance,sustainability-medium" type="String" description="classification"/>
<property name="xpath">
<value><![CDATA[
//MethodDeclaration//MethodCall[pmd-java:matchesSig('javax.xml.xpath.XPath#compile(java.lang.String)') or
pmd-java:matchesSig('javax.xml.xpath.XPath#evaluate(java.lang.String,java.lang.Object,javax.xml.namespace.QName)')]
]]></value>
</property>
</properties>
<example>
<![CDATA[
class Bad {
public static NodeList bad1(Document doc) {
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile("//book[author='Isaac Asimov']/title/text()"); // bad
return (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
}
public static NodeList bad2(Document doc) throws XPathExpressionException {
XPath xpath = XPathFactory.newInstance().newXPath();
String xPathQuery = "//book[author='Isaac Asimov']/title/text()";
return (NodeList) xpath.evaluate(xPathQuery, doc, XPathConstants.NODESET); // bad
}
}
class Good {
private static final ThreadLocal<XPathFactory> tlFac = ThreadLocal.withInitial(XPathFactory::newInstance);
private static final ThreadLocal<XPathExpression> tlExpr;
static {
XPath xpath = tlFac.get().newXPath();
try {
XPathExpression expr = xpath.compile("//book[author='Isaac Asimov']/title/text()");
tlExpr = ThreadLocal.withInitial(() -> expr); // good
} catch (XPathExpressionException e) {
throw new RuntimeException(e);
}
}
public static NodeList good(Document doc) throws XPathExpressionException {
return (NodeList) tlExpr.get().evaluate(doc, XPathConstants.NODESET); // good
}
}
]]>
</example>
</rule>
<rule name="AvoidRecreatingDateTimeFormatter"
message="Avoid recreating DateTimeFormatter, it is relatively expensive."
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule" language="java"
externalInfoUrl="https://github.com/jborgers/PMD-jPinpoint-rules/tree/pmd7/docs/JavaCodePerformance.md#idtf02">
<description>
Problem: Recreating a DateTimeFormatter is relatively expensive.
Solution: Java 8+ java.time.DateTimeFormatter is thread-safe and can be shared among threads. Create the
formatter from a pattern only once, to initialize a static final field.
(jpinpoint-rules)</description>
<priority>2</priority>
<properties>
<property name="tags" value="cpu,jpinpoint-rule,performance,sustainability-medium" type="String" description="classification"/>
<property name="xpath">
<value>
<![CDATA[
//FieldDeclaration
[ClassType[pmd-java:typeIs('java.time.format.DateTimeFormatter') or pmd-java:typeIs('org.joda.time.format.DateTimeFormatter')]]
[(not(pmd-java:modifiers() = 'static') and VariableDeclarator[@Initializer=true()]) or not(pmd-java:modifiers() = 'final')]
|
//MethodDeclaration//ConstructorCall[pmd-java:matchesSig('org.joda.time.format.DateTimeFormatter#new(_,_)')]
|
//(MethodDeclaration|ConstructorDeclaration)//MethodCall[((pmd-java:matchesSig('java.time.format.DateTimeFormatter#ofPattern(_)')
or pmd-java:matchesSig('org.joda.time.format.DateTimeFormat#forPattern(_)'))
and not(ArgumentList/VariableAccess/@Name = ancestor::Block/..//FormalParameter/VariableId/@Name))
or pmd-java:matchesSig('java.time.format.DateTimeFormatterBuilder#toFormatter()')
or pmd-java:matchesSig('java.time.format.DateTimeFormatterBuilder#toFormatter(_)')
or pmd-java:matchesSig('org.joda.time.format.DateTimeFormatterBuilder#toFormatter()')
or pmd-java:matchesSig('org.joda.time.format.ISODateTimeFormat#_()')
or pmd-java:matchesSig('org.joda.time.format.DateTimeFormat#fullDateTime()')
]
]]>
</value>
</property>
</properties>
</rule>
<rule name="AvoidRecreatingSecurityProviders"
language="java"
message="Avoid re-creating security providers, this is expensive."
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule"
externalInfoUrl="https://github.com/jborgers/PMD-jPinpoint-rules/tree/pmd7/docs/JavaCodePerformance.md#iuosf01">
<description>Problem: Creating a security provider is expensive because of loading of algorithms and other classes. Additionally, it uses synchronized which leads to lock contention when used with multiple threads.
Solution: This only needs to happen once in the JVM lifetime, because once loaded, the provider is typically available from the Security class. Create the security provider only once: only in case it is nog available from the Security class, yet.
(jpinpoint-rules)</description>
<priority>2</priority>
<properties>
<property name="tags" value="cpu,io,jpinpoint-rule,performance,sustainability-high" type="String" description="classification"/>
<property name="xpath">
<value><![CDATA[
//MethodDeclaration
[not((@Name='main' and @Static=true())or ModifierList/Annotation/@SimpleName='PostConstruct'
or .//IfStatement//InfixExpression
[@Operator='=='][VariableAccess[pmd-java:typeIs('java.security.Provider')] and NullLiteral]
)]
//ConstructorCall[pmd-java:typeIs('java.security.Provider') or pmd-java:typeIs('org.bouncycastle.jce.provider.BouncyCastleProvider')]
]]></value>
</property>
</properties>
<example>
<![CDATA[
import java.security.*;
import javax.crypto.*;
import org.bouncycastle.jce.provider.*;
class Foo {
public Cipher initBlowfishBad() throws GeneralSecurityException {
Security.addProvider(new BouncyCastleProvider()); // bad
// build a Cipher
}
public Cipher initBlowfishGood() throws GeneralSecurityException {
Provider bouncyCastleProvider = Security.getProvider(BouncyCastleProvider.PROVIDER_NAME);
if (bouncyCastleProvider == null) {
bouncyCastleProvider = new BouncyCastleProvider();
Security.addProvider(bouncyCastleProvider);
}
// build a Cipher
}
}
]]>
</example>
</rule>
<rule name="AvoidReflectionInToStringAndHashCode"
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule"
language="java"
message="Reflection is used in toString or hashCode, which is expensive."
externalInfoUrl="https://github.com/jborgers/PMD-jPinpoint-rules/tree/pmd7/docs/JavaCodePerformance.md#uuor01">
<description>Problem: Reflection is relatively expensive.
Solution: Avoid to use reflection. Use the non-reflective, explicit way, like generation by IDE or Lombok.
(jpinpoint-rules)</description>
<priority>2</priority>
<properties>
<property name="tags" value="cpu,jpinpoint-rule,performance,sustainability-high" type="String" description="classification"/>
<property name="xpath">
<value><![CDATA[
//MethodCall[starts-with(@MethodName, 'reflection')][(TypeExpression|ConstructorCall)
[pmd-java:typeIs('org.apache.commons.lang3.builder.EqualsBuilder') or pmd-java:typeIs('org.apache.commons.lang3.builder.HashCodeBuilder')]]
]]>
</value>
</property>
</properties>
<example>
<![CDATA[
class Bad {
private int state;
public boolean equals(Object o) {
return EqualsBuilder.reflectionEquals(o, this); // bad
}
}
class Good {
private int state;
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Good)) return false;
return new EqualsBuilder().append(((Good)o).state, state).isEquals();
}
}
]]>
</example>
</rule>
<rule name="AvoidSimpleDateFormat"
class="net.sourceforge.pmd.lang.rule.xpath.XPathRule"
language="java"
message="SimpleDateFormat is used. Since it is thread-unsafe, it needs expensive recreation."
externalInfoUrl="https://github.com/jborgers/PMD-jPinpoint-rules/tree/pmd7/docs/JavaCodePerformance.md#idtf01">
<description>Problem: java.util.SimpleDateFormat is thread-unsafe. The usual solution is to create a new one when needed in a method. Creating SimpleDateFormat is relatively expensive.
Solution: Use java.time.DateTimeFormatter. These classes are immutable, thus thread-safe and can be made static.
(jpinpoint-rules)</description>
<priority>2</priority>
<properties>
<property name="tags" value="cpu,jpinpoint-rule,performance,sustainability-medium" type="String" description="classification"/>
<property name="xpath">
<value><![CDATA[
//ConstructorCall/ClassType[pmd-java:typeIs('java.text.SimpleDateFormat')
and not ((ancestor::LocalVariableDeclaration/following-sibling::ExpressionStatement/MethodCall|ancestor::MethodCall)
[@MethodName='setDateFormat']/VariableAccess[pmd-java:typeIs('com.fasterxml.jackson.databind.ObjectMapper')
or pmd-java:typeIs('com.fasterxml.jackson.dataformat.xml.XmlMapper')])
]
]]></value>
</property>