Showing 467 of 569 total issues
Make this method "synchronized" to match the parent class implementation. Open
public void mark(final int readLimit) {
- Read upRead up
- Exclude checks
When @Overrides
of synchronized
methods are not themselves synchronized
, the result can be improper
synchronization as callers rely on the thread-safety promised by the parent class.
Noncompliant Code Example
public class Parent { synchronized void foo() { //... } } public class Child extends Parent { @Override public void foo () { // Noncompliant // ... super.foo(); } }
Compliant Solution
public class Parent { synchronized void foo() { //... } } public class Child extends Parent { @Override synchronized void foo () { // ... super.foo(); } }
See
- CERT, TSM00-J - Do not override thread-safe methods with methods that are not thread-safe
Make this method "synchronized" to match the parent class implementation. Open
public void mark(final int readLimit) {
- Read upRead up
- Exclude checks
When @Overrides
of synchronized
methods are not themselves synchronized
, the result can be improper
synchronization as callers rely on the thread-safety promised by the parent class.
Noncompliant Code Example
public class Parent { synchronized void foo() { //... } } public class Child extends Parent { @Override public void foo () { // Noncompliant // ... super.foo(); } }
Compliant Solution
public class Parent { synchronized void foo() { //... } } public class Child extends Parent { @Override synchronized void foo () { // ... super.foo(); } }
See
- CERT, TSM00-J - Do not override thread-safe methods with methods that are not thread-safe
Rename "buff" which hides the field declared at line 22. Open
var buff = this.buff;
- 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
Rename "compressor" which hides the field declared at line 40. Open
final var compressor = new Deflater(compressionLevel);
- 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
Make this method "synchronized" to match the parent class implementation. Open
public void mark(final int limit) {
- Read upRead up
- Exclude checks
When @Overrides
of synchronized
methods are not themselves synchronized
, the result can be improper
synchronization as callers rely on the thread-safety promised by the parent class.
Noncompliant Code Example
public class Parent { synchronized void foo() { //... } } public class Child extends Parent { @Override public void foo () { // Noncompliant // ... super.foo(); } }
Compliant Solution
public class Parent { synchronized void foo() { //... } } public class Child extends Parent { @Override synchronized void foo () { // ... super.foo(); } }
See
- CERT, TSM00-J - Do not override thread-safe methods with methods that are not thread-safe
Return an empty array instead of null. Open
return null;
- Read upRead up
- Exclude checks
Returning null
instead of an actual array or collection forces callers of the method to explicitly test for nullity, making them more
complex and less readable.
Moreover, in many cases, null
is used as a synonym for empty.
Noncompliant Code Example
public static List<Result> getResults() { return null; // Noncompliant } public static Result[] getResults() { return null; // Noncompliant } public static void main(String[] args) { Result[] results = getResults(); if (results != null) { // Nullity test required to prevent NPE for (Result result: results) { /* ... */ } } }
Compliant Solution
public static List<Result> getResults() { return Collections.emptyList(); // Compliant } public static Result[] getResults() { return new Result[0]; } public static void main(String[] args) { for (Result result: getResults()) { /* ... */ } }
See
- CERT, MSC19-C. - For functions that return an array, prefer returning an empty array over a null value
- CERT, MET55-J. - Return an empty array or collection instead of a null value for methods that return an array or collection
Define a constant instead of duplicating this literal "selfsigned" 3 times. Open
"-alias", "selfsigned", //
- 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.
Either re-interrupt this method or rethrow the "InterruptedException" that can be caught here. Open
} catch (final InterruptedException ex) {
- Read upRead up
- Exclude checks
InterruptedExceptions
should never be ignored in the code, and simply logging the exception counts in this case as "ignoring". The
throwing of the InterruptedException
clears the interrupted state of the Thread, so if the exception is not handled properly the fact
that the thread was interrupted will be lost. Instead, InterruptedExceptions
should either be rethrown - immediately or after cleaning up
the method's state - or the thread should be re-interrupted by calling Thread.interrupt()
even if this is supposed to be a
single-threaded application. Any other course of action risks delaying thread shutdown and loses the information that the thread was interrupted -
probably without finishing its task.
Similarly, the ThreadDeath
exception should also be propagated. According to its JavaDoc:
If
ThreadDeath
is caught by a method, it is important that it be rethrown so that the thread actually dies.
Noncompliant Code Example
public void run () { try { while (true) { // do stuff } }catch (InterruptedException e) { // Noncompliant; logging is not enough LOGGER.log(Level.WARN, "Interrupted!", e); } }
Compliant Solution
public void run () { try { while (true) { // do stuff } }catch (InterruptedException e) { LOGGER.log(Level.WARN, "Interrupted!", e); // Restore interrupted state... Thread.currentThread().interrupt(); } }
See
- MITRE, CWE-391 - Unchecked Error Condition
- Dealing with InterruptedException
Add the missing @deprecated Javadoc tag. Open
public abstract class DelegatingSecurityManagerWithThreadLocalControl extends DelegatingSecurityManager {
- 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(); }
Define a constant instead of duplicating this literal "] is not a regular file." 4 times. Open
throw _createIllegalStateException("Resource [" + file.getAbsolutePath() + "] is not a regular file.");
- 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.
Remove this useless assignment; "value" already holds the assigned value along all execution paths. Open
value = _notNull(argumentName, value);
- Read upRead up
- Exclude checks
The transitive property says that if a == b
and b == c
, then a == c
. In such cases, there's no point in
assigning a
to c
or vice versa because they're already equivalent.
This rule raises an issue when an assignment is useless because the assigned-to variable already holds the value on all execution paths.
Noncompliant Code Example
a = b; c = a; b = c; // Noncompliant: c and b are already the same
Compliant Solution
a = b; c = a;
Define a constant instead of duplicating this literal " but is " 12 times. Open
throw _createIllegalArgumentException(argumentName, "must be greater than " + bound + " but is " + 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.
Define a constant instead of duplicating this literal "serviceInterface" 3 times. Open
Args.notNull("serviceInterface", serviceInterface);
- 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 19 to the 15 allowed. Open
protected <SERVICE_INTERFACE> ServiceProxyInternal<SERVICE_INTERFACE> createServiceProxy(final ServiceEndpointState serviceEndpointState,
- 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
Define and throw a dedicated exception instead of using a generic one. Open
public @Nullable Object intercept(@Origin final Method method, @AllArguments final Object... args) throws Exception {
- Read upRead up
- Exclude checks
Using such generic exceptions as Error
, RuntimeException
, Throwable
, and Exception
prevents
calling methods from handling true, system-generated exceptions differently than application-generated errors.
Noncompliant Code Example
public void foo(String bar) throws Throwable { // Noncompliant throw new RuntimeException("My Message"); // Noncompliant }
Compliant Solution
public void foo(String bar) { throw new MyOwnRuntimeException("My Message"); }
Exceptions
Generic exceptions in the signatures of overriding methods are ignored, because overriding method has to follow signature of the throw declaration in the superclass. The issue will be raised on superclass declaration of the method (or won't be raised at all if superclass is not part of the analysis).
@Override public void myMethod() throws Exception {...}
Generic exceptions are also ignored in the signatures of methods that make calls to methods that throw generic exceptions.
public void myOtherMethod throws Exception { doTheThing(); // this method throws Exception }
See
- MITRE, CWE-397 - Declaration of Throws for Generic Exception
- CERT, ERR07-J. - Do not throw RuntimeException, Exception, or Throwable
Define a constant instead of duplicating this literal "tableName" 7 times. Open
Args.notEmpty("tableName", tableName);
- 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 "columnNames" 3 times. Open
Args.notEmpty("columnNames", columnNames);
- 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.
Add a nested comment explaining why this method is empty, throw an UnsupportedOperationException or complete the implementation. Open
public void destroy() {
- Read upRead up
- Exclude checks
There are several reasons for a method not to have a method body:
- It is an unintentional omission, and should be fixed to prevent an unexpected behavior in production.
- It is not yet, or never will be, supported. In this case an
UnsupportedOperationException
should be thrown. - The method is an intentionally-blank override. In this case a nested comment should explain the reason for the blank override.
Noncompliant Code Example
public void doSomething() { } public void doSomethingElse() { }
Compliant Solution
@Override public void doSomething() { // Do nothing because of X and Y. } @Override public void doSomethingElse() { throw new UnsupportedOperationException(); }
Exceptions
Default (no-argument) constructors are ignored when there are other constructors in the class, as are empty methods in abstract classes.
public abstract class Animal { void speak() { // default implementation ignored } }
Use static access with "javax.xml.stream.XMLStreamConstants" for "CHARACTERS". Open
case XMLStreamReader.CHARACTERS: {
- Read upRead up
- Exclude checks
In the interest of code clarity, static
members of a base
class should never be accessed using a derived type's name.
Doing so is confusing and could create the illusion that two different static members exist.
Noncompliant Code Example
class Parent { public static int counter; } class Child extends Parent { public Child() { Child.counter++; // Noncompliant } }
Compliant Solution
class Parent { public static int counter; } class Child extends Parent { public Child() { Parent.counter++; } }
Use static access with "javax.xml.stream.XMLStreamConstants" for "END_ELEMENT". Open
case XMLStreamReader.END_ELEMENT: {
- Read upRead up
- Exclude checks
In the interest of code clarity, static
members of a base
class should never be accessed using a derived type's name.
Doing so is confusing and could create the illusion that two different static members exist.
Noncompliant Code Example
class Parent { public static int counter; } class Child extends Parent { public Child() { Child.counter++; // Noncompliant } }
Compliant Solution
class Parent { public static int counter; } class Child extends Parent { public Child() { Parent.counter++; } }