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
When logging a message there are several important requirements which must be fulfilled:
The user must be able to easily retrieve the logs
The format of all logged message must be uniform to allow the user to easily read the log
Logged data must actually be recorded
Sensitive data must only be logged securely
If a program directly writes to the standard outputs, there is absolutely no way to comply with those requirements. That's why defining and using a
dedicated logger is highly recommended.
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
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
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.
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
When logging a message there are several important requirements which must be fulfilled:
The user must be able to easily retrieve the logs
The format of all logged message must be uniform to allow the user to easily read the log
Logged data must actually be recorded
Sensitive data must only be logged securely
If a program directly writes to the standard outputs, there is absolutely no way to comply with those requirements. That's why defining and using a
dedicated logger is highly recommended.
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.
public String getReadableStatus(Job j) {
if (j.isRunning()) {
return "Running";
}
return j.hasErrors() ? "Failed" : "Succeeded";
}
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
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
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.
Programmers should not comment out code as it bloats programs and reduces readability.
Unused code should be deleted and can be retrieved from source control history if required.
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.
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.
public String getReadableStatus(Job j) {
if (j.isRunning()) {
return "Running";
}
return j.hasErrors() ? "Failed" : "Succeeded";
}
When logging a message there are several important requirements which must be fulfilled:
The user must be able to easily retrieve the logs
The format of all logged message must be uniform to allow the user to easily read the log
Logged data must actually be recorded
Sensitive data must only be logged securely
If a program directly writes to the standard outputs, there is absolutely no way to comply with those requirements. That's why defining and using a
dedicated logger is highly recommended.
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
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
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
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
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