Showing 1,225 of 1,229 total issues
Invoke method(s) only conditionally. Open
logger.info(format(("%s: Unknown action %s, ignore! action: %<s %s!%n"), DcmAgent.class.getName(), action, argumentString));
- Read upRead up
- Create a ticketCreate a ticket
- Exclude checks
Passing message arguments that require further evaluation into a Guava com.google.common.base.Preconditions
check can result in a
performance penalty. That's because whether or not they're needed, each argument must be resolved before the method is actually called.
Similarly, passing concatenated strings into a logging method can also incur a needless performance hit because the concatenation will be performed every time the method is called, whether or not the log level is low enough to show the message.
Instead, you should structure your code to pass static or pre-computed values into Preconditions
conditions check and logging
calls.
Specifically, the built-in string formatting should be used instead of string concatenation, and if the message is the result of a method call,
then Preconditions
should be skipped altogether, and the relevant exception should be conditionally thrown instead.
Noncompliant Code Example
logger.log(Level.DEBUG, "Something went wrong: " + message); // Noncompliant; string concatenation performed even when log level too high to show DEBUG messages logger.fine("An exception occurred with message: " + message); // Noncompliant LOG.error("Unable to open file " + csvPath, e); // Noncompliant Preconditions.checkState(a > 0, "Arg must be positive, but got " + a); // Noncompliant. String concatenation performed even when a > 0 Preconditions.checkState(condition, formatMessage()); // Noncompliant. formatMessage() invoked regardless of condition Preconditions.checkState(condition, "message: %s", formatMessage()); // Noncompliant
Compliant Solution
logger.log(Level.SEVERE, "Something went wrong: {0} ", message); // String formatting only applied if needed logger.fine("An exception occurred with message: {}", message); // SLF4J, Log4j logger.log(Level.SEVERE, () -> "Something went wrong: " + message); // since Java 8, we can use Supplier , which will be evaluated lazily LOG.error("Unable to open file {0}", csvPath, e); if (LOG.isDebugEnabled() { LOG.debug("Unable to open file " + csvPath, e); // this is compliant, because it will not evaluate if log level is above debug. } Preconditions.checkState(arg > 0, "Arg must be positive, but got %d", a); // String formatting only applied if needed if (!condition) { throw new IllegalStateException(formatMessage()); // formatMessage() only invoked conditionally } if (!condition) { throw new IllegalStateException("message: " + formatMessage()); }
Exceptions
catch
blocks are ignored, because the performance penalty is unimportant on exceptional paths (catch block should not be a part of
standard program flow). Getters are ignored as well as methods called on annotations which can be considered as getters. This rule accounts for
explicit test-level testing with SLF4J methods isXXXEnabled
and ignores the bodies of such if
statements.
Add a private constructor to hide the implicit public one. Open
public class DcmAgent {
- Read upRead up
- Create a ticketCreate a ticket
- 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.
Replace this use of System.out or System.err by a logger. Open
System.out.println("Invalid input, not number!");
- Read upRead up
- Create a ticketCreate a ticket
- Exclude checks
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.
Noncompliant Code Example
System.out.println("My Message"); // Noncompliant
Compliant Solution
logger.log("My Message");
See
- CERT, ERR02-J. - Prevent exceptions while logging data
This accessibility update should be removed. Open
f.setAccessible(true);
- Read upRead up
- Create a ticketCreate a ticket
- Exclude checks
This rule raises an issue when reflection is used to change the visibility of a class, method or field, and when it is used to directly update a field value. Altering or bypassing the accessibility of classes, methods, or fields violates the encapsulation principle and could lead to run-time errors.
Noncompliant Code Example
public void makeItPublic(String methodName) throws NoSuchMethodException { this.getClass().getMethod(methodName).setAccessible(true); // Noncompliant } public void setItAnyway(String fieldName, int value) { this.getClass().getDeclaredField(fieldName).setInt(this, value); // Noncompliant; bypasses controls in setter }
See
- CERT, SEC05-J. - Do not use reflection to increase accessibility of classes, methods, or fields
Replace this use of System.out or System.err by a logger. Open
System.out.println(line);
- Read upRead up
- Create a ticketCreate a ticket
- Exclude checks
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.
Noncompliant Code Example
System.out.println("My Message"); // Noncompliant
Compliant Solution
logger.log("My Message");
See
- CERT, ERR02-J. - Prevent exceptions while logging data