Conditional expressions which are always true or false can lead to dead code. Such code is always buggy and should never
be used in production.
Noncompliant Code Example
a = false;
if (a) { // Noncompliant
doSomething(); // never executed
}
if (!a || b) { // Noncompliant; "!a" is always "true", "b" is never evaluated
doSomething();
} else {
doSomethingElse(); // never executed
}
Exceptions
This rule will not raise an issue in either of these cases:
When the condition is a single final boolean
final boolean debug = false;
//...
if (debug) {
// Print something
}
When the condition is literally true or false.
if (true) {
// do something
}
In these cases it is obvious the code is as intended.
CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
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
Generic types shouldn't be used raw (without type parameters) in variable declarations or return values. Doing so bypasses generic type checking,
and defers the catch of unsafe code to runtime.
Noncompliant Code Example
List myList; // Noncompliant
Set mySet; // Noncompliant
Compliant Solution
List<String> myList;
Set<? extends Number> mySet;
A reference to null should never be dereferenced/accessed. Doing so will cause a NullPointerException to be thrown. At
best, such an exception will cause abrupt program termination. At worst, it could expose debugging information that would be useful to an attacker, or
it could allow an attacker to bypass security measures.
Note that when they are present, this rule takes advantage of @CheckForNull and @Nonnull annotations defined in JSR-305 to understand which values are and are not nullable except when @Nonnull is used
on the parameter to equals, which by contract should always work with null.
Noncompliant Code Example
@CheckForNull
String getName(){...}
public boolean isNameEmpty() {
return getName().length() == 0; // Noncompliant; the result of getName() could be null, but isn't null-checked
}
Connection conn = null;
Statement stmt = null;
try{
conn = DriverManager.getConnection(DB_URL,USER,PASS);
stmt = conn.createStatement();
// ...
}catch(Exception e){
e.printStackTrace();
}finally{
stmt.close(); // Noncompliant; stmt could be null if an exception was thrown in the try{} block
conn.close(); // Noncompliant; conn could be null if an exception was thrown
}
private void merge(@Nonnull Color firstColor, @Nonnull Color secondColor){...}
public void append(@CheckForNull Color color) {
merge(currentColor, color); // Noncompliant; color should be null-checked because merge(...) doesn't accept nullable parameters
}
void paint(Color color) {
if(color == null) {
System.out.println("Unable to apply color " + color.toString()); // Noncompliant; NullPointerException will be thrown
return;
}
...
}
CERT, EXP01-J. - Do not use a null in a case where an object is required
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
Generic types shouldn't be used raw (without type parameters) in variable declarations or return values. Doing so bypasses generic type checking,
and defers the catch of unsafe code to runtime.
Noncompliant Code Example
List myList; // Noncompliant
Set mySet; // Noncompliant
Compliant Solution
List<String> myList;
Set<? extends Number> mySet;
Abstract classes should not have public constructors. Constructors of abstract classes can only be called in constructors of their subclasses. So
there is no point in making them public. The protected modifier should be enough.
Noncompliant Code Example
public abstract class AbstractClass1 {
public AbstractClass1 () { // Noncompliant, has public modifier
// do something here
}
}
Compliant Solution
public abstract class AbstractClass2 {
protected AbstractClass2 () {
// do something here
}
}
Generic types shouldn't be used raw (without type parameters) in variable declarations or return values. Doing so bypasses generic type checking,
and defers the catch of unsafe code to runtime.
Noncompliant Code Example
List myList; // Noncompliant
Set mySet; // Noncompliant
Compliant Solution
List<String> myList;
Set<? extends Number> mySet;
Conditional expressions which are always true or false can lead to dead code. Such code is always buggy and should never
be used in production.
Noncompliant Code Example
a = false;
if (a) { // Noncompliant
doSomething(); // never executed
}
if (!a || b) { // Noncompliant; "!a" is always "true", "b" is never evaluated
doSomething();
} else {
doSomethingElse(); // never executed
}
Exceptions
This rule will not raise an issue in either of these cases:
When the condition is a single final boolean
final boolean debug = false;
//...
if (debug) {
// Print something
}
When the condition is literally true or false.
if (true) {
// do something
}
In these cases it is obvious the code is as intended.
CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
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 or LinkedList instead of Vector
Deque instead of Stack
HashMap instead of Hashtable
StringBuilder instead of StringBuffer
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() {...}
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