Showing 467 of 569 total issues
Make "compareTo" transient or serializable. Open
public final V compareTo;
- Read upRead up
- Exclude checks
Fields in a Serializable
class must themselves be either Serializable
or transient
even if the class is
never explicitly serialized or deserialized. For instance, under load, most J2EE application frameworks flush objects to disk, and an allegedly
Serializable
object with non-transient, non-serializable data members could cause program crashes, and open the door to attackers. In
general a Serializable
class is expected to fulfil its contract and not have an unexpected behaviour when an instance is serialized.
This rule raises an issue on non-Serializable
fields, and on collection fields when they are not private
(because they
could be assigned non-Serializable
values externally), and when they are assigned non-Serializable
types within the
class.
Noncompliant Code Example
public class Address { //... } public class Person implements Serializable { private static final long serialVersionUID = 1905122041950251207L; private String name; private Address address; // Noncompliant; Address isn't serializable }
Compliant Solution
public class Address implements Serializable { private static final long serialVersionUID = 2405172041950251807L; } public class Person implements Serializable { private static final long serialVersionUID = 1905122041950251207L; private String name; private Address address; }
Exceptions
The alternative to making all members serializable
or transient
is to implement special methods which take on the
responsibility of properly serializing and de-serializing the object. This rule ignores classes which implement the following methods:
private void writeObject(java.io.ObjectOutputStream out) throws IOException private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException;
See
- MITRE, CWE-594 - Saving Unserializable Objects to Disk
- Oracle Java 6, Serializable
- Oracle Java 7, Serializable
Add a private constructor to hide the implicit public one. Open
public abstract class Enumerations {
- Read upRead up
- Exclude checks
Utility classes, which are collections of static
members, are not meant to be instantiated. Even abstract utility classes, which can
be extended, should not have public constructors.
Java adds an implicit public constructor to every class which does not define at least one explicitly. Hence, at least one non-public constructor should be defined.
Noncompliant Code Example
class StringUtils { // Noncompliant public static String concatenate(String s1, String s2) { return s1 + s2; } }
Compliant Solution
class StringUtils { // Compliant private StringUtils() { throw new IllegalStateException("Utility class"); } public static String concatenate(String s1, String s2) { return s1 + s2; } }
Exceptions
When class contains public static void main(String[] args)
method it is not considered as utility class and will be ignored by this
rule.
Rename this class. Open
public abstract class ArrayUtils extends org.apache.commons.lang3.ArrayUtils {
- Read upRead up
- Exclude checks
While it's perfectly legal to give a class the same simple name as a class in another package that it extends or interface it implements, it's confusing and could cause problems in the future.
Noncompliant Code Example
package my.mypackage; public class Foo implements a.b.Foo { // Noncompliant
Compliant Solution
package my.mypackage; public class FooJr implements a.b.Foo {
Remove usage of generic wildcard type. Open
public static <K, V> CompletableFuture<?> forEachWithIndexConcurrent(final @Nullable Map<K, V> map,
- Read upRead up
- Exclude checks
It is highly recommended not to use wildcard types as return types. Because the type inference rules are fairly complex it is unlikely the user of that API will know how to use it correctly.
Let's take the example of method returning a "List<? extends Animal>". Is it possible on this list to add a Dog, a Cat, ... we simply don't know. And neither does the compiler, which is why it will not allow such a direct use. The use of wildcard types should be limited to method parameters.
This rule raises an issue when a method returns a wildcard type.
Noncompliant Code Example
List<? extends Animal> getAnimals(){...}
Compliant Solution
List<Animal> getAnimals(){...}
or
List<Dog> getAnimals(){...}
Define a constant instead of duplicating this literal "values" 3 times. Open
Args.notNull("values", values);
- Read upRead up
- Exclude checks
Duplicated string literals make the process of refactoring error-prone, since you must be sure to update all occurrences.
On the other hand, constants can be referenced from many places, but only need to be updated in a single place.
Noncompliant Code Example
With the default threshold of 3:
public void run() { prepare("action1"); // Noncompliant - "action1" is duplicated 3 times execute("action1"); release("action1"); } @SuppressWarning("all") // Compliant - annotations are excluded private void method1() { /* ... */ } @SuppressWarning("all") private void method2() { /* ... */ } public String method3(String a) { System.out.println("'" + a + "'"); // Compliant - literal "'" has less than 5 characters and is excluded return ""; // Compliant - literal "" has less than 5 characters and is excluded }
Compliant Solution
private static final String ACTION_1 = "action1"; // Compliant public void run() { prepare(ACTION_1); // Compliant execute(ACTION_1); release(ACTION_1); }
Exceptions
To prevent generating some false-positives, literals having less than 5 characters are excluded.
Refactor this method to reduce its Cognitive Complexity from 28 to the 15 allowed. Open
public static <K, V extends Comparable<V>> @NonNull Map<K, V> sortByValue(final @NonNull Map<K, V> map,
- Read upRead up
- Exclude checks
Cognitive Complexity is a measure of how hard the control flow of a method is to understand. Methods with high Cognitive Complexity will be difficult to maintain.
See
Add a private constructor to hide the implicit public one. Open
public abstract class Iterators {
- Read upRead up
- Exclude checks
Utility classes, which are collections of static
members, are not meant to be instantiated. Even abstract utility classes, which can
be extended, should not have public constructors.
Java adds an implicit public constructor to every class which does not define at least one explicitly. Hence, at least one non-public constructor should be defined.
Noncompliant Code Example
class StringUtils { // Noncompliant public static String concatenate(String s1, String s2) { return s1 + s2; } }
Compliant Solution
class StringUtils { // Compliant private StringUtils() { throw new IllegalStateException("Utility class"); } public static String concatenate(String s1, String s2) { return s1 + s2; } }
Exceptions
When class contains public static void main(String[] args)
method it is not considered as utility class and will be ignored by this
rule.
Remove this call to "wait" or move it into a "while" loop. Open
obj.wait(millis);
- Read upRead up
- Exclude checks
According to the documentation of the Java Condition
interface:
When waiting upon a
Condition
, a "spurious wakeup" is permitted to occur, in general, as a concession to the underlying platform semantics. This has little practical impact on most application programs as a Condition should always be waited upon in a loop, testing the state predicate that is being waited for. An implementation is free to remove the possibility of spurious wakeups but it is recommended that applications programmers always assume that they can occur and so always wait in a loop.
The same advice is also found for the Object.wait(...)
method:
waits should always occur in loops, like this one:
synchronized (obj) { while (<condition does not hold>){ obj.wait(timeout); } ... // Perform action appropriate to condition }
Noncompliant Code Example
synchronized (obj) { if (!suitableCondition()){ obj.wait(timeout); //the thread can wake up even if the condition is still false } ... // Perform action appropriate to condition }
Compliant Solution
synchronized (obj) { while (!suitableCondition()){ obj.wait(timeout); } ... // Perform action appropriate to condition }
See
- CERT THI03-J. - Always invoke wait() and await() methods inside a loop
Replace the synchronized class "StringBuffer" by an unsynchronized one such as "StringBuilder". Open
public void dumpThreads(final StringBuffer out) {
- Read upRead up
- Exclude checks
Early classes of the Java API, such as Vector
, Hashtable
and StringBuffer
, were synchronized to make them
thread-safe. Unfortunately, synchronization has a big negative impact on performance, even when using these collections from a single thread.
It is better to use their new unsynchronized replacements:
-
ArrayList
orLinkedList
instead ofVector
-
Deque
instead ofStack
-
HashMap
instead ofHashtable
-
StringBuilder
instead ofStringBuffer
Even when used in synchronized context, you should think twice before using it, since it's usage can be tricky. If you are confident the usage is legitimate, you can safely ignore this warning.
Noncompliant Code Example
Vector cats = new Vector();
Compliant Solution
ArrayList cats = new ArrayList();
Exceptions
Use of those synchronized classes is ignored in the signatures of overriding methods.
@Override public Vector getCats() {...}
Rename "thread" which hides the field declared at line 91. Open
final var thread = this.thread;
- Read upRead up
- Exclude checks
Overriding or shadowing a variable declared in an outer scope can strongly impact the readability, and therefore the maintainability, of a piece of code. Further, it could lead maintainers to introduce bugs because they think they're using one variable but are really using another.
Noncompliant Code Example
class Foo { public int myField; public void doSomething() { int myField = 0; ... } }
See
- CERT, DCL01-C. - Do not reuse variable names in subscopes
- CERT, DCL51-J. - Do not shadow or obscure identifiers in subscopes
Add a private constructor to hide the implicit public one. Open
public abstract class SafeAwait {
- Read upRead up
- Exclude checks
Utility classes, which are collections of static
members, are not meant to be instantiated. Even abstract utility classes, which can
be extended, should not have public constructors.
Java adds an implicit public constructor to every class which does not define at least one explicitly. Hence, at least one non-public constructor should be defined.
Noncompliant Code Example
class StringUtils { // Noncompliant public static String concatenate(String s1, String s2) { return s1 + s2; } }
Compliant Solution
class StringUtils { // Compliant private StringUtils() { throw new IllegalStateException("Utility class"); } public static String concatenate(String s1, String s2) { return s1 + s2; } }
Exceptions
When class contains public static void main(String[] args)
method it is not considered as utility class and will be ignored by this
rule.
Add the missing @deprecated Javadoc tag. Open
public void setHours(final int i) throws UnsupportedOperationException {
- Read upRead up
- Exclude checks
Deprecation should be marked with both the @Deprecated
annotation and @deprecated Javadoc tag. The annotation enables tools such as
IDEs to warn about referencing deprecated elements, and the tag can be used to explain when it was deprecated, why, and how references should be
refactored.
Further, Java 9 adds two additional arguments to the annotation:
-
since
allows you to describe when the deprecation took place -
forRemoval
, indicates whether the deprecated element will be removed at some future date
If your compile level is Java 9 or higher, you should be using one or both of these arguments.
Noncompliant Code Example
class MyClass { @Deprecated public void foo1() { } /** * @deprecated */ public void foo2() { // Noncompliant } }
Compliant Solution
class MyClass { /** * @deprecated (when, why, refactoring advice...) */ @Deprecated public void foo1() { } /** * Java >= 9 * @deprecated (when, why, refactoring advice...) */ @Deprecated(since="5.1") public void foo2() { } /** * Java >= 9 * @deprecated (when, why, refactoring advice...) */ @Deprecated(since="4.2", forRemoval=true) public void foo3() { } }
Exceptions
The members and methods of a deprecated class or interface are ignored by this rule. The classes and interfaces themselves are still subject to it.
/** * @deprecated (when, why, etc...) */ @Deprecated class Qix { public void foo() {} // Compliant; class is deprecated } /** * @deprecated (when, why, etc...) */ @Deprecated interface Plop { void bar(); }
Remove this expression which always evaluates to "false" Open
if (parent == null || targetAccessor == null)
- Read upRead up
- Exclude checks
If a boolean expression doesn't change the evaluation of the condition, then it is entirely unnecessary, and can be removed. If it is gratuitous because it does not match the programmer's intent, then it's a bug and the expression should be fixed.
Noncompliant Code Example
a = true; if (a) { // Noncompliant doSomething(); } if (b && a) { // Noncompliant; "a" is always "true" doSomething(); } if (c || !a) { // Noncompliant; "!a" is always "false" doSomething(); }
Compliant Solution
a = true; if (foo(a)) { doSomething(); } if (b) { doSomething(); } if (c) { doSomething(); }
See
- MITRE, CWE-571 - Expression is Always True
- MITRE, CWE-570 - Expression is Always False
Refactor this method to reduce its Cognitive Complexity from 34 to the 15 allowed. Open
private void _log(final Level level, final @Nullable String message, final @Nullable Throwable ex, final boolean isDebugLevelEnabled) {
- Read upRead up
- Exclude checks
Cognitive Complexity is a measure of how hard the control flow of a method is to understand. Methods with high Cognitive Complexity will be difficult to maintain.
See
Synchronize this method to match the synchronization on "setEncoding". Open
public String getEncoding() {
- Read upRead up
- Exclude checks
When one part of a getter/setter pair is synchronized
the other part should be too. Failure to synchronize both sides of a pair may
result in inconsistent behavior at runtime as callers access an inconsistent method state.
This rule raises an issue when either the method or the contents of one method in a getter/setter pair are synchrnoized but the other is not.
Noncompliant Code Example
public class Person { String name; int age; public synchronized void setName(String name) { this.name = name; } public String getName() { // Noncompliant return this.name; } public void setAge(int age) { // Noncompliant this.age = age; } public int getAge() { synchronized (this) { return this.age; } } }
Compliant Solution
public class Person { String name; int age; public synchronized void setName(String name) { this.name = name; } public synchronized String getName() { return this.name; } public void setAge(int age) { synchronized (this) { this.age = age; } } public int getAge() { synchronized (this) { return this.age; } } }
See
- CERT, VNA01-J. - Ensure visibility of shared references to immutable objects
Define a constant instead of duplicating this literal "beanType" 3 times. Open
Args.notNull("beanType", beanType);
- Read upRead up
- Exclude checks
Duplicated string literals make the process of refactoring error-prone, since you must be sure to update all occurrences.
On the other hand, constants can be referenced from many places, but only need to be updated in a single place.
Noncompliant Code Example
With the default threshold of 3:
public void run() { prepare("action1"); // Noncompliant - "action1" is duplicated 3 times execute("action1"); release("action1"); } @SuppressWarning("all") // Compliant - annotations are excluded private void method1() { /* ... */ } @SuppressWarning("all") private void method2() { /* ... */ } public String method3(String a) { System.out.println("'" + a + "'"); // Compliant - literal "'" has less than 5 characters and is excluded return ""; // Compliant - literal "" has less than 5 characters and is excluded }
Compliant Solution
private static final String ACTION_1 = "action1"; // Compliant public void run() { prepare(ACTION_1); // Compliant execute(ACTION_1); release(ACTION_1); }
Exceptions
To prevent generating some false-positives, literals having less than 5 characters are excluded.
Extract this nested try block into a separate method. Open
try {
- Read upRead up
- Exclude checks
Nesting try
/catch
blocks severely impacts the readability of source code because it makes it too difficult to understand
which block will catch which exception.
Rename this class. Open
public abstract class SerializationUtils extends org.apache.commons.lang3.SerializationUtils {
- Read upRead up
- Exclude checks
While it's perfectly legal to give a class the same simple name as a class in another package that it extends or interface it implements, it's confusing and could cause problems in the future.
Noncompliant Code Example
package my.mypackage; public class Foo implements a.b.Foo { // Noncompliant
Compliant Solution
package my.mypackage; public class FooJr implements a.b.Foo {
Define a constant instead of duplicating this literal "compressed" 4 times. Open
Args.notNull("compressed", compressed);
- Read upRead up
- Exclude checks
Duplicated string literals make the process of refactoring error-prone, since you must be sure to update all occurrences.
On the other hand, constants can be referenced from many places, but only need to be updated in a single place.
Noncompliant Code Example
With the default threshold of 3:
public void run() { prepare("action1"); // Noncompliant - "action1" is duplicated 3 times execute("action1"); release("action1"); } @SuppressWarning("all") // Compliant - annotations are excluded private void method1() { /* ... */ } @SuppressWarning("all") private void method2() { /* ... */ } public String method3(String a) { System.out.println("'" + a + "'"); // Compliant - literal "'" has less than 5 characters and is excluded return ""; // Compliant - literal "" has less than 5 characters and is excluded }
Compliant Solution
private static final String ACTION_1 = "action1"; // Compliant public void run() { prepare(ACTION_1); // Compliant execute(ACTION_1); release(ACTION_1); }
Exceptions
To prevent generating some false-positives, literals having less than 5 characters are excluded.
Define a constant instead of duplicating this literal "Source InputStream is closed!" 3 times. Open
throw new IOException("Source InputStream is closed!");
- Read upRead up
- Exclude checks
Duplicated string literals make the process of refactoring error-prone, since you must be sure to update all occurrences.
On the other hand, constants can be referenced from many places, but only need to be updated in a single place.
Noncompliant Code Example
With the default threshold of 3:
public void run() { prepare("action1"); // Noncompliant - "action1" is duplicated 3 times execute("action1"); release("action1"); } @SuppressWarning("all") // Compliant - annotations are excluded private void method1() { /* ... */ } @SuppressWarning("all") private void method2() { /* ... */ } public String method3(String a) { System.out.println("'" + a + "'"); // Compliant - literal "'" has less than 5 characters and is excluded return ""; // Compliant - literal "" has less than 5 characters and is excluded }
Compliant Solution
private static final String ACTION_1 = "action1"; // Compliant public void run() { prepare(ACTION_1); // Compliant execute(ACTION_1); release(ACTION_1); }
Exceptions
To prevent generating some false-positives, literals having less than 5 characters are excluded.