Showing 467 of 569 total issues
Catch Exception instead of Throwable. Open
} catch (final Throwable t) { // CHECKSTYLE:IGNORE IllegalCatch
- Read upRead up
- Exclude checks
Throwable
is the superclass of all errors and exceptions in Java. Error
is the superclass of all errors, which are not
meant to be caught by applications.
Catching either Throwable
or Error
will also catch OutOfMemoryError
and InternalError
, from
which an application should not attempt to recover.
Noncompliant Code Example
try { /* ... */ } catch (Throwable t) { /* ... */ } try { /* ... */ } catch (Error e) { /* ... */ }
Compliant Solution
try { /* ... */ } catch (RuntimeException e) { /* ... */ } try { /* ... */ } catch (MyException e) { /* ... */ }
See
- MITRE, CWE-396 - Declaration of Catch for Generic Exception
- C++ Core Guidelines E.14 - Use purpose-designed user-defined types as exceptions (not built-in types)
Define a constant instead of duplicating this literal "value" 7 times. Open
Args.notNull("value", value);
- 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.
Catch Exception instead of Throwable. Open
} catch (final Throwable t) { // CHECKSTYLE:IGNORE IllegalCatch
- Read upRead up
- Exclude checks
Throwable
is the superclass of all errors and exceptions in Java. Error
is the superclass of all errors, which are not
meant to be caught by applications.
Catching either Throwable
or Error
will also catch OutOfMemoryError
and InternalError
, from
which an application should not attempt to recover.
Noncompliant Code Example
try { /* ... */ } catch (Throwable t) { /* ... */ } try { /* ... */ } catch (Error e) { /* ... */ }
Compliant Solution
try { /* ... */ } catch (RuntimeException e) { /* ... */ } try { /* ... */ } catch (MyException e) { /* ... */ }
See
- MITRE, CWE-396 - Declaration of Catch for Generic Exception
- C++ Core Guidelines E.14 - Use purpose-designed user-defined types as exceptions (not built-in types)
Rename "executor" which hides the field declared at line 30. Open
final var executor = this.executor;
- 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
Refactor the code in order to not assign to this loop counter from within the loop body. Open
idx += 2;
- Read upRead up
- Exclude checks
A for
loop stop condition should test the loop counter against an invariant value (i.e. one that is true at both the beginning and
ending of every loop iteration). Ideally, this means that the stop condition is set to a local variable just before the loop begins.
Stop conditions that are not invariant are slightly less efficient, as well as being difficult to understand and maintain, and likely lead to the introduction of errors in the future.
This rule tracks three types of non-invariant stop conditions:
- When the loop counters are updated in the body of the
for
loop - When the stop condition depend upon a method call
- When the stop condition depends on an object property, since such properties could change during the execution of the loop.
Noncompliant Code Example
for (int i = 0; i < 10; i++) { ... i = i - 1; // Noncompliant; counter updated in the body of the loop ... }
Compliant Solution
for (int i = 0; i < 10; i++) {...}
Make "second" transient or serializable. Open
private final Function<? super Intermediate, Out> second;
- 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
Refactor this method to reduce its Cognitive Complexity from 35 to the 15 allowed. Open
public static CharSequence ansiColorsToHTML(final CharSequence txt, final @Nullable ANSIState initialState) {
- 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
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
"lock" is a method parameter, and should not be used for synchronization. Open
synchronized (lock) {
return delegate.get();
}
- Read upRead up
- Exclude checks
Synchronizing on a class field synchronizes not on the field itself, but on the object assigned to it. So synchronizing on a non-final
field makes it possible for the field's value to change while a thread is in a block synchronized on the old value. That would allow a second thread,
synchronized on the new value, to enter the block at the same time.
The story is very similar for synchronizing on parameters; two different threads running the method in parallel could pass two different object instances in to the method as parameters, completely undermining the synchronization.
Noncompliant Code Example
private String color = "red"; private void doSomething(){ synchronized(color) { // Noncompliant; lock is actually on object instance "red" referred to by the color variable //... color = "green"; // other threads now allowed into this block // ... } synchronized(new Object()) { // Noncompliant this is a no-op. // ... } }
Compliant Solution
private String color = "red"; private final Object lockObj = new Object(); private void doSomething(){ synchronized(lockObj) { //... color = "green"; // ... } }
See
- MITRE, CWE-412 - Unrestricted Externally Accessible Lock
- MITRE, CWE-413 - Improper Resource Locking
- CERT, LCK00-J. - Use private final lock objects to synchronize classes that may interact with untrusted code
Extract this nested ternary operation into an independent statement. Open
: d1 > d2 //
? 1
: 0;
- Read upRead up
- Exclude checks
Just because you can do something, doesn't mean you should, and that's the case with nested ternary operations. Nesting ternary operators results in the kind of code that may seem clear as day when you write it, but six months later will leave maintainers (or worse - future you) scratching their heads and cursing.
Instead, err on the side of clarity, and use another line to express the nested operation as a separate statement.
Noncompliant Code Example
public String getReadableStatus(Job j) { return j.isRunning() ? "Running" : j.hasErrors() ? "Failed" : "Succeeded"; // Noncompliant }
Compliant Solution
public String getReadableStatus(Job j) { if (j.isRunning()) { return "Running"; } return j.hasErrors() ? "Failed" : "Succeeded"; }
Remove this unused method parameter "searchFor". Open
public static int countMatches(final @Nullable String searchIn, final char searchFor) {
- Read upRead up
- Exclude checks
Unused parameters are misleading. Whatever the values passed to such parameters, the behavior will be the same.
Noncompliant Code Example
void doSomething(int a, int b) { // "b" is unused compute(a); }
Compliant Solution
void doSomething(int a) { compute(a); }
Exceptions
The rule will not raise issues for unused parameters:
- that are annotated with
@javax.enterprise.event.Observes
- in overrides and implementation methods
- in interface
default
methods - in non-private methods that only
throw
or that have empty bodies - in annotated methods, unless the annotation is
@SuppressWarning("unchecked")
or@SuppressWarning("rawtypes")
, in which case the annotation will be ignored - in overridable methods (non-final, or not member of a final class, non-static, non-private), if the parameter is documented with a proper javadoc.
@Override void doSomething(int a, int b) { // no issue reported on b compute(a); } public void foo(String s) { // designed to be extended but noop in standard case } protected void bar(String s) { //open-closed principle } public void qix(String s) { throw new UnsupportedOperationException("This method should be implemented in subclasses"); } /** * @param s This string may be use for further computation in overriding classes */ protected void foobar(int a, String s) { // no issue, method is overridable and unused parameter has proper javadoc compute(a); }
See
- CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
Refactor this method to reduce its Cognitive Complexity from 20 to the 15 allowed. Open
public static String replaceEach(final String searchIn, final String @Nullable [] searchFor, final String @Nullable [] replaceWith) {
- 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 Predicates {
- 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.
Refactor this method to reduce its Cognitive Complexity from 19 to the 15 allowed. Open
public static @NonNull String @Nullable [] splitLinesNullable(final @Nullable String text, final boolean preserveEmptyLines) {
- 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
Refactor this method to reduce its Cognitive Complexity from 21 to the 15 allowed. Open
public static void replaceEach(final @Nullable StringBuilder searchIn, final String @Nullable [] searchFor,
- 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
Remove usage of generic wildcard type. Open
public static <T> CompletableFuture<?> forEachWithIndexConcurrent(final @Nullable Enumeration<T> en, @Nullable ExecutorService workers,
- 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(){...}
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(){...}
Make "item" transient or serializable. Open
private T item;
- 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
Refactor this method to reduce its Cognitive Complexity from 25 to the 15 allowed. Open
public static boolean openURLInBrowser(final String url) {
- 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 the missing @deprecated Javadoc tag. Open
public void setTime(final long date) 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(); }