Rules which enforce generally accepted best practices. 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. 3 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. 3 When accessing a private field / method from another class, the Java compiler will generate a 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. 3 Constructors and methods receiving arrays should clone objects and store the copy. This prevents future changes from the user from affecting the original array. 3 Avoid printStackTrace(); use a logger call instead. 3 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._ 3 Reassigning values to incoming parameters is not recommended. Use temporary local variables instead. 2 StringBuffers/StringBuilders can grow considerably, and so may become a source of memory leaks if held within objects with long lifetimes. 3 Application with hard-coded IP addresses can become impossible to deploy in some cases. Externalizing IP adresses is preferable. 3 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. 3 Avoid constants in interfaces. Interfaces should define types, constants are implementation details better placed in classes or enums. See Effective Java, item 19. 3 By convention, the default label should be the last label in a switch statement. 3 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. 3 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); } } } ]]> 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. 3 //ForInit/LocalVariableDeclaration[count(VariableDeclarator) > $maximumVariables] Whenever using a log level, one should check if the loglevel is actually enabled, or otherwise skip the associate String creation and manipulation. 2 In JUnit 3, test suites are indicated by the suite() method. In JUnit 4, suites are indicated through the @RunWith(Suite.class) annotation. 3 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. JUnit 5 introduced @AfterEach and @AfterAll annotations to execute methods after each test or after all tests in the class, respectively. 3 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. JUnit 5 introduced @BeforeEach and @BeforeAll annotations to execute methods before each test or before all tests in the class, respectively. 3 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. In JUnit 5, one of the following annotations should be used for tests: @Test, @RepeatedTest, @TestFactory, @TestTemplate or @ParameterizedTest. 3 JUnit assertions should include an informative message - i.e., use the three-argument version of assertEquals(), not the two-argument version. 3 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 JUnit4, JUnit5 and TestNG Tests, as well as methods starting with "test". 3 $maximumAsserts] ]]> 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. 3 In JUnit4, use the @Test(expected) annotation to denote tests that should throw exceptions. 3 The use of implementation types (i.e., HashSet) as object references limits your ability to use alternate implementations in the future as requirements change. Whenever available, referencing objects by their interface types (i.e, Set) provides much more flexibility. 3 list = new ArrayList<>(); public HashSet getFoo() { return new HashSet(); } // preferred approach private List list = new ArrayList<>(); public Set getFoo() { return new HashSet(); } } ]]> 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. 3 Annotating overridden methods with @Override ensures at compile time that the method really overrides one, which helps refactoring and clarifies intent. 3 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. 4 1] [$strictMode or count(distinct-values(VariableDeclarator/@BeginLine)) != count(VariableDeclarator)] | //FieldDeclaration [count(VariableDeclarator) > 1] [$strictMode or count(distinct-values(VariableDeclarator/@BeginLine)) != count(VariableDeclarator)] ]]> Position literals first in comparisons, if the second argument is null then NullPointerExceptions can be avoided, they will just return false. 3 Position literals first in comparisons, if the second argument is null then NullPointerExceptions can be avoided, they will just return false. 3 Throwing a new exception from a catch block without passing the original exception into the new exception will cause the original stack trace to be lost making it difficult to debug effectively. 3 Consider replacing Enumeration usages with the newer java.util.Iterator 3 Consider replacing Hashtable usage with the newer java.util.Map if thread safety is not required. 3 //Type/ReferenceType/ClassOrInterfaceType[@Image='Hashtable'] Consider replacing Vector usages with the newer java.util.ArrayList if expensive thread-safe operations are not required. 3 //Type/ReferenceType/ClassOrInterfaceType[@Image='Vector'] All switch statements should include a default option to catch any unspecified values. 3 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. 2 Avoid passing parameters to methods or constructors without actually referencing them in the method body. 3 Avoid unused import statements to prevent unwanted dependencies. This rule will also find unused on demand imports, i.e. import com.foo.*. 4 Detects when a local variable is declared and/or assigned, but not used. 3 Detects when a private field is declared and/or assigned a value, but not used. 3 Unused Private Method detects when a private method is declared but is unused. 3 This rule detects JUnit assertions in object equality. These assertions should be made by more specific methods, like assertEquals. 3 This rule detects JUnit assertions in object references equality. These assertions should be made by more specific methods, like assertNull, assertNotNull. 3 This rule detects JUnit assertions in object references equality. These assertions should be made by more specific methods, like assertSame, assertNotSame. 3 When asserting a value is the same as a literal or Boxed boolean, use assertTrue/assertFalse, instead of assertEquals. 3 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. 3 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. 3 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. 4