GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — pmd/pmd-java/src/main/resources/category/java/bestpractices.xml at main · pmd/pmd Expand file tree/ Copy pathbestpractices.xmlMore file actions 2488 lines (2266 loc) · 93.8 KB / Copy pathbestpractices.xmlFile metadata and controls2488 lines (2266 loc) · 93.8 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="Best Practices" 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 https://pmd.sourceforge.io/ruleset_2_0_0.xsd"> <description> Rules which enforce generally accepted best practices. </description> <rule name="AbstractClassWithoutAbstractMethod" language="java" since="3.0" message="This abstract class does not have any abstract methods" class="net.sourceforge.pmd.lang.java.rule.bestpractices.AbstractClassWithoutAbstractMethodRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_bestpractices.html#abstractclasswithoutabstractmethod"> <description> 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. </description> <priority>3</priority> <example> <![CDATA[ public abstract class Foo { void int method1() { ... } void int method2() { ... } // consider using abstract methods or removing // the abstract modifier and adding protected constructors } ]]> </example> </rule> <rule name="AccessorClassGeneration" language="java" since="1.04" maximumLanguageVersion="10" message="Avoid instantiation through private constructors from outside of the constructor's class." class="net.sourceforge.pmd.lang.java.rule.bestpractices.AccessorClassGenerationRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_bestpractices.html#accessorclassgeneration"> <description> 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](https://openjdk.org/jeps/181) has been implemented. This means that in Java 11 and above accessor classes are not generated anymore. </description> <priority>3</priority> <example> <![CDATA[ public class Outer { void method(){ Inner ic = new Inner();//Causes generation of accessor class } public class Inner { private Inner(){} } } ]]> </example> </rule> <rule name="AccessorMethodGeneration" language="java" since="5.5.4" maximumLanguageVersion="10" message="Consider giving this member package visibility to access it from {0} without a synthetic accessor method" class="net.sourceforge.pmd.lang.java.rule.bestpractices.AccessorMethodGenerationRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_bestpractices.html#accessormethodgeneration"> <description> 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](https://openjdk.org/jeps/181) has been implemented. This means that in Java 11 and above accessor classes are not generated anymore. </description> <priority>3</priority> <example> <![CDATA[ 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 } } } ]]> </example> </rule> <rule name="ArrayIsStoredDirectly" language="java" since="2.2" message="The user-supplied array ''{0}'' is stored directly." class="net.sourceforge.pmd.lang.java.rule.bestpractices.ArrayIsStoredDirectlyRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_bestpractices.html#arrayisstoreddirectly"> <description> Constructors and methods receiving arrays should clone objects and store the copy. This prevents future changes from the user from affecting the original array. </description> <priority>3</priority> <example> <![CDATA[ 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; } } ]]> </example> </rule> <rule name="AssertStatementInTest" language="java" since="7.25.0" message="Assert statements should not be used in test code." class="net.sourceforge.pmd.lang.java.rule.bestpractices.AssertStatementInTestRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_bestpractices.html#assertstatementintest"> <description> Assert statements should not be used in test code. Instead, use the assertion methods provided by the testing framework, such as JUnit 4's `Assert`, JUnit Jupiter's `Assertions` or TestNG's `Assert` class. These helper methods provide better error messages and make test code more readable. They also are not disabled when tests are run without `-ea`. </description> <priority>3</priority> <example> <![CDATA[ import org.junit.Test; public class FooTest { @Test public void testSomething() { assert Foo.bar == 1; // violation, should use Assert.assertEquals(1, Foo.bar); } } ]]> </example> </rule> <rule name="AvoidMessageDigestField" language="java" since="6.18.0" message="You shouldn't declare field of MessageDigest type, because unsynchronized access could cause problems" class="net.sourceforge.pmd.lang.rule.xpath.XPathRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_bestpractices.html#avoidmessagedigestfield"> <description> 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. </description> <priority>3</priority> <properties> <property name="xpath"> <value> <![CDATA[ //FieldDeclaration/ClassType[pmd-java:typeIs('java.security.MessageDigest')] ]]> </value> </property> </properties> <example> <![CDATA[ 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(); } } ]]> </example> </rule> <rule name="AvoidPrintStackTrace" language="java" since="3.2" message="Avoid printStackTrace(); use a logger call instead." class="net.sourceforge.pmd.lang.rule.xpath.XPathRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_bestpractices.html#avoidprintstacktrace"> <description> Avoid printStackTrace(); use a logger call instead. </description> <priority>3</priority> <properties> <property name="xpath"> <value> <![CDATA[ //MethodCall[ pmd-java:matchesSig("java.lang.Throwable#printStackTrace()") ] ]]> </value> </property> </properties> <example> <![CDATA[ class Foo { void bar() { try { // do something } catch (Exception e) { e.printStackTrace(); } } } ]]> </example> </rule> <rule name="AvoidReassigningCatchVariables" language="java" since="6.27.0" message="Avoid reassigning caught exception ''{0}''" class="net.sourceforge.pmd.lang.java.rule.bestpractices.AvoidReassigningCatchVariablesRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_bestpractices.html#avoidreassigningcatchvariables"> <description> 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. </description> <priority>3</priority> <example><![CDATA[ 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 } } } ]]></example> </rule> <rule name="AvoidReassigningLoopVariables" language="java" since="6.11.0" message="Avoid reassigning the loop control variable ''{0}''" class="net.sourceforge.pmd.lang.java.rule.bestpractices.AvoidReassigningLoopVariablesRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_bestpractices.html#avoidreassigningloopvariables"> <description> 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: - `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._ In for-loops, configured by the `forReassign` property: - `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._ </description> <priority>3</priority> <example> <![CDATA[ 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); } } } ]]> </example> </rule> <rule name="AvoidReassigningParameters" language="java" since="1.0" message="Avoid reassigning parameters such as ''{0}''" class="net.sourceforge.pmd.lang.java.rule.bestpractices.AvoidReassigningParametersRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_bestpractices.html#avoidreassigningparameters"> <description> 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. </description> <priority>2</priority> <example> <![CDATA[ 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); } } ]]> </example> </rule> <rule name="AvoidStringBufferField" language="java" since="4.2" message="StringBuffers can grow quite a lot, and so may become a source of memory leak (if the owning class has a long life time)." class="net.sourceforge.pmd.lang.rule.xpath.XPathRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_bestpractices.html#avoidstringbufferfield"> <description> StringBuffers/StringBuilders can grow considerably, and so may become a source of memory leaks if held within objects with long lifetimes. </description> <priority>3</priority> <properties> <property name="xpath"> <value> <![CDATA[ //FieldDeclaration/ClassType[pmd-java:typeIs('java.lang.StringBuffer') or pmd-java:typeIs('java.lang.StringBuilder')] ]]> </value> </property> </properties> <example> <![CDATA[ public class Foo { private StringBuffer buffer; // potential memory leak as an instance variable; } ]]> </example> </rule> <rule name="AvoidUsingHardCodedIP" language="java" since="4.1" message="Do not hard code the IP address ''{0}''" class="net.sourceforge.pmd.lang.java.rule.bestpractices.AvoidUsingHardCodedIPRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_bestpractices.html#avoidusinghardcodedip"> <description> Application with hard-coded IP addresses can become impossible to deploy in some cases. Externalizing IP addresses is preferable. </description> <priority>3</priority> <example> <![CDATA[ public class Foo { private String ip = "127.0.0.1"; // not recommended } ]]> </example> </rule> <rule name="CheckResultSet" language="java" since="4.1" class="net.sourceforge.pmd.lang.java.rule.bestpractices.CheckResultSetRule" message="Always check the return of one of the navigation method (next,previous,first,last) of a ResultSet." externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_bestpractices.html#checkresultset"> <description> 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. </description> <priority>3</priority> <example> <![CDATA[ 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 } ]]> </example> </rule> <rule name="ConstantsInInterface" language="java" since="5.5" message="Using constants in interfaces is a bad practice." class="net.sourceforge.pmd.lang.rule.xpath.XPathRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_bestpractices.html#constantsininterface"> <description> 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'. </description> <priority>3</priority> <properties> <property name="ignoreIfHasMethods" type="Boolean" description="Whether to ignore constants in interfaces if the interface defines any methods" value="true"/> <property name="xpath"> <value> <![CDATA[ //ClassDeclaration[@Interface = true()][$ignoreIfHasMethods= false() or not(ClassBody/MethodDeclaration)]/ClassBody/FieldDeclaration ]]> </value> </property> </properties> <example> <![CDATA[ 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(); } ]]> </example> </rule> <rule name="ControlFlowInTest" language="java" since="7.30.0" message="Control flow in a test can obscure its assertions" class="net.sourceforge.pmd.lang.java.rule.bestpractices.ControlFlowInTestRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_bestpractices.html#controlflowintest"> <description> Control flow in test methods can make it difficult to determine which assertions are executed and whether all intended cases are covered. This rule reports if statements, conditional expressions, switch statements and expressions, explicit throw statements, try statements with catch clauses, and plain try-finally statements. Loops are allowed by default. Set the property `allowLoops` to `false` to report for, enhanced for, while, and do-while loops as well. Other control flow inside an allowed loop is still reported. Prefer concrete examples or parameterized tests over conditional assertions. Use `assertThrows` or `assertDoesNotThrow` instead of manually catching exceptions. The rule checks test methods recognized by PMD's JUnit and TestNG support, including lambda bodies within those methods. Methods and initializers of local or anonymous classes are not treated as part of the enclosing test. Try-with-resources statements without catch clauses are allowed. Plain try-finally statements are reported; prefer an @AfterEach method for test cleanup where appropriate. </description> <priority>3</priority> <example><![CDATA[ import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; class ExampleTest { @Test void checksValueConditionally() { int value = Integer.parseInt("42"); if (value > 0) { // violation assertEquals(42, value); } } @Test void checksConcreteValue() { assertEquals(42, Integer.parseInt("42")); } } ]]></example> </rule> <rule name="DefaultLabelNotLastInSwitchStmt" deprecated="true" ref="DefaultLabelNotLastInSwitch" /> <rule name="DefaultLabelNotLastInSwitch" language="java" since="1.5" message="The default label should be the last label in a switch statement or expression" class="net.sourceforge.pmd.lang.rule.xpath.XPathRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_bestpractices.html#defaultlabelnotlastinswitch"> <description> 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. </description> <priority>3</priority> <properties> <property name="xpath"> <value> <![CDATA[ //SwitchLabel[@Default = true() and not(.. is ../../*[last()])] ]]> </value> </property> </properties> <example> <![CDATA[ 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; } } } ]]> </example> </rule> <rule name="DoubleBraceInitialization" language="java" since="6.16.0" message="Double-brace initialization should be avoided" class="net.sourceforge.pmd.lang.rule.xpath.XPathRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_bestpractices.html#doublebraceinitialization"> <description> 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. </description> <priority>3</priority> <properties> <property name="xpath"> <value> <![CDATA[ //ConstructorCall/AnonymousClassDeclaration/ClassBody[count(*)=1]/Initializer[@Static=false()] ]]> </value> </property> </properties> <example><![CDATA[ // 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; ]]> </example> </rule> <rule name="EnumComparison" language="java" since="7.19.0" message="Enums should be compared using ==" class="net.sourceforge.pmd.lang.rule.xpath.XPathRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_bestpractices.html#enumcomparison"> <description> When comparing enums, `equals()` should be avoided and `==` should be preferred. Using `==` has some advantages: * same semantic as `equals()` * less problematic with possible null pointer exceptions * supports static type check: If you compare two incompatible enum types, the compiler will tell you. When using equals, you'll only get noticed at runtime or not at all. This rule implements SonarSource rule [S4551](https://sonarsource.github.io/rspec/#/rspec/S4551). Note, that only primitive types and enums should be compared using `==`. To compare other objects, `equals()` is the correct way. See {%rule java/errorprone/CompareObjectsWithEquals %} and {%rule java/errorprone/UseEqualsToCompareStrings %}. </description> <priority>3</priority> <properties> <property name="xpath"> <value><![CDATA[ //MethodCall[pmd-java:matchesSig("_#equals(java.lang.Object)")] [*[pmd-java:typeIs("java.lang.Enum")] or ArgumentList[*[pmd-java:typeIs("java.lang.Enum")]]] ]]></value> </property> </properties> <example><![CDATA[ enum Color { RED, GREEN, BLUE } class ColorTester { boolean isRed(Color color) { return color.equals(Color.RED); // violation } boolean isGreen(Color color) { return color == Color.GREEN; // preferred } } ]]></example> </rule> <rule name="ExhaustiveSwitchHasDefault" language="java" since="7.10.0" message="Replace default case with explicit cases{0} to make sure compiler keeps checking that all cases are present." class="net.sourceforge.pmd.lang.java.rule.bestpractices.ExhaustiveSwitchHasDefaultRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_bestpractices.html#exhaustiveswitchhasdefault"> <description> 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. Note 2: The compiler doesn't create a compilation error for a switch *statement* over an enum that is non-exhaustive. When enabling this rule, you should consider also enabling the rule {% rule NonExhaustiveSwitch %}, so that you are still notified, if someone adds a new enum constant and that new constant is not covered in an existing switch statement that previously was exhaustive but now is not anymore. </description> <priority>3</priority> <example> <![CDATA[ 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"); }; } } ]]> </example> </rule> <rule name="ForLoopCanBeForeach" language="java" since="6.0.0" message="This 'for' loop can be replaced by a 'foreach' loop" minimumLanguageVersion="1.5" class="net.sourceforge.pmd.lang.java.rule.bestpractices.ForLoopCanBeForeachRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_bestpractices.html#forloopcanbeforeach"> <description> 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. </description> <priority>3</priority> <example> <![CDATA[ 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); } } } ]]> </example> </rule> <rule name="ForLoopVariableCount" language="java" since="6.11.0" message="Too many control variables in the 'for' statement" class="net.sourceforge.pmd.lang.rule.xpath.XPathRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_bestpractices.html#forloopvariablecount"> <description> 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. </description> <priority>3</priority> <properties> <property name="maximumVariables" type="Integer" description="A regular for statement will have 1 control variable" min="0" max="100" value="1"/> <property name="xpath"> <value>//ForInit/LocalVariableDeclaration[count(VariableDeclarator) > $maximumVariables]</value> </property> </properties> <example> <![CDATA[ // 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(); ]]> </example> </rule> <rule name="GuardLogStatement" language="java" since="5.1.0" message="Logger calls should be surrounded by log level guards." class="net.sourceforge.pmd.lang.java.rule.bestpractices.GuardLogStatementRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_bestpractices.html#guardlogstatement"> <description> 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. </description> <priority>2</priority> <example> <![CDATA[ // 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); ]]> </example> </rule> <rule name="ImplicitFunctionalInterface" language="java" since="7.12.0" message="Annotate this interface with @FunctionalInterface or with @SuppressWarnings("PMD.ImplicitFunctionalInterface") to clarify your intent." class="net.sourceforge.pmd.lang.java.rule.bestpractices.ImplicitFunctionalInterfaceRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_bestpractices.html#implicitfunctionalinterface"> <description> 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. </description> <priority>2</priority> <example> <![CDATA[ // 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(); } ]]> </example> </rule> <rule name="JUnit4SuitesShouldUseSuiteAnnotation" language="java" since="4.0" message="JUnit 4 indicates test suites via annotations, not the suite method." class="net.sourceforge.pmd.lang.rule.xpath.XPathRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_bestpractices.html#junit4suitesshouldusesuiteannotation"> <description> In JUnit 3, test suites are indicated by the suite() method. In JUnit 4, suites are indicated through the @RunWith(Suite.class) annotation. </description> <priority>3</priority> <properties> <property name="xpath"> <value> <![CDATA[ //MethodDeclaration[@Name='suite' and ClassType[pmd-java:typeIs('junit.framework.Test')]] [not(.//ReturnStatement/*[pmd-java:typeIs('junit.framework.JUnit4TestAdapter')])] ]]> </value> </property> </properties> <example> <![CDATA[ public class BadExample extends TestCase{ public static Test suite(){ return new Suite(); } } @RunWith(Suite.class) @SuiteClasses( { TestOne.class, TestTwo.class }) public class GoodTest { } ]]> </example> </rule> <rule name="JUnit4TestShouldUseAfterAnnotation" deprecated="true" ref="UnitTestShouldUseAfterAnnotation" /> <rule name="JUnit4TestShouldUseBeforeAnnotation" deprecated="true" ref="UnitTestShouldUseBeforeAnnotation"/> <rule name="JUnit4TestShouldUseTestAnnotation" deprecated="true" ref="UnitTestShouldUseTestAnnotation" /> <rule name="JUnit5TestShouldBePackagePrivate" deprecated="true" ref="JUnitJupiterTestShouldBePackagePrivate" /> <rule name="JUnitJupiterTestShouldBePackagePrivate" language="java" since="6.35.0" message="JUnit 5 tests should be package-private." class="net.sourceforge.pmd.lang.java.rule.bestpractices.JUnitJupiterTestShouldBePackagePrivateRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_bestpractices.html#junitjupitertestshouldbepackageprivate"> <description><![CDATA[ Reports JUnit Jupiter 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 Jupiter 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`. Note: This rule was named `JUnit5TestShouldBePackagePrivate` before PMD 7.25.0. ]]></description> <priority>3</priority> <example> <![CDATA[ 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 } ]]> </example> </rule> <rule name="JUnitAssertionsShouldIncludeMessage" deprecated="true" ref="UnitTestAssertionsShouldIncludeMessage" /> <rule name="JUnitTestContainsTooManyAsserts" deprecated="true" ref="UnitTestContainsTooManyAsserts"/> <rule name="JUnitTestsShouldIncludeAssert" deprecated="true" ref="UnitTestShouldIncludeAssert" /> <rule name="JUnitUseExpected" language="java" since="4.0" message="In JUnit4, use the @Test(expected) annotation to denote tests that should throw exceptions" class="net.sourceforge.pmd.lang.java.rule.bestpractices.JUnitUseExpectedRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_bestpractices.html#junituseexpected"> <description> In JUnit4, use the @Test(expected) annotation to denote tests that should throw exceptions. </description> <priority>3</priority> <example> <![CDATA[ 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(); } } ]]> </example> </rule> <rule name="LabeledStatement" language="java" since="7.18.0" message="Avoid using labeled statements such as ''{0}''." class="net.sourceforge.pmd.lang.rule.xpath.XPathRule" externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_bestpractices.html#labeledstatement"> <description> This rule detects the use of labeled statements. By default, it allows labeled loops so that you can use `break` / `continue` with labels. This can be changed with the property `allowLoops` to flag any labels. Labels make control flow difficult to understand and should be avoided. They can be confused with the goto statement and make code harder to read and maintain. If you really need to jump out of an inner loop, think about refactoring the multiple loops into a function - that way, you can replace the break with a return. This rule implements SonarSource rule [S1119](https://sonarsource.github.io/rspec/#/rspec/S1119). To detect unused labels, use the rule {% rule UnusedLabel %}. </description> <priority>3</priority> <properties> <property name="xpath"> <value> <![CDATA[ if ($allowLoops) then //LabeledStatement[not(DoStatement|WhileStatement|ForStatement|ForeachStatement)][let $label := @Label return (.//BreakStatement | .//ContinueStatement)[@Label = $label] ] else //LabeledStatement[let $label := @Label return (.//BreakStatement | .//ContinueStatement)[@Label = $label] ] ]]> </value> </property> <property name="allowLoops" type="Boolean" description="Whether to allow or not allow labels before loop statements (do, while, for)" value="true" /> </properties> <example> <![CDATA[ |
| You are visitor 01402775 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |