Showing 76 of 76 total issues
Provide the parametrized type for this generic. Open
Map<String, Collection<Class>> getReactionIdsToObjectTypesMap();
- Read upRead up
- Exclude checks
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;
Provide the parametrized type for this generic. Open
public Map<String, Collection<Class>> getReactionIdsToObjectTypesMap() {
- Read upRead up
- Exclude checks
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;
Invoke method(s) only conditionally. Open
logger.finest(reactionIdsToObjectTypeMap.toString());
- Read upRead up
- 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 ReflectionUtils {
- 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.
Provide the parametrized type for this generic. Open
private Map<String, Map<Class, List<Method>>> reactionIdToObjectTypeToMethodMap = new HashMap<>();
- Read upRead up
- Exclude checks
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;
Provide the parametrized type for this generic. Open
Map<Class, List<Method>> objectTypeToHandlersMap = new HashMap<>();
- Read upRead up
- Exclude checks
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;
Lambda should be used to defer string concatenation. Open
logger.log(Level.WARNING, "Failed to invoke [method=" +
method.getName() + "],[reactionId=" + reactionId + "]", e);
- Read upRead up
- Exclude checks
Because printf
-style format strings are interpreted at runtime, rather than validated by the compiler, they can contain errors that
result in the wrong strings being created. This rule statically validates the correlation of printf
-style format strings to their
arguments when calling the format(...)
methods of java.util.Formatter
, java.lang.String
,
java.io.PrintStream
, MessageFormat
, and java.io.PrintWriter
classes and the printf(...)
methods of
java.io.PrintStream
or java.io.PrintWriter
classes.
Noncompliant Code Example
String.format("First {0} and then {1}", "foo", "bar"); //Noncompliant. Looks like there is a confusion with the use of {{java.text.MessageFormat}}, parameters "foo" and "bar" will be simply ignored here String.format("Display %3$d and then %d", 1, 2, 3); //Noncompliant; the second argument '2' is unused String.format("Too many arguments %d and %d", 1, 2, 3); //Noncompliant; the third argument '3' is unused String.format("First Line\n"); //Noncompliant; %n should be used in place of \n to produce the platform-specific line separator String.format("Is myObject null ? %b", myObject); //Noncompliant; when a non-boolean argument is formatted with %b, it prints true for any nonnull value, and false for null. Even if intended, this is misleading. It's better to directly inject the boolean value (myObject == null in this case) String.format("value is " + value); // Noncompliant String s = String.format("string without arguments"); // Noncompliant MessageFormat.format("Result '{0}'.", value); // Noncompliant; String contains no format specifiers. (quote are discarding format specifiers) MessageFormat.format("Result {0}.", value, value); // Noncompliant; 2nd argument is not used MessageFormat.format("Result {0}.", myObject.toString()); // Noncompliant; no need to call toString() on objects java.util.Logger logger; logger.log(java.util.logging.Level.SEVERE, "Result {0}.", myObject.toString()); // Noncompliant; no need to call toString() on objects logger.log(java.util.logging.Level.SEVERE, "Result.", new Exception()); // compliant, parameter is an exception logger.log(java.util.logging.Level.SEVERE, "Result '{0}'", 14); // Noncompliant - String contains no format specifiers. logger.log(java.util.logging.Level.SEVERE, "Result " + param, exception); // Noncompliant; Lambda should be used to differ string concatenation. org.slf4j.Logger slf4jLog; org.slf4j.Marker marker; slf4jLog.debug(marker, "message {}"); slf4jLog.debug(marker, "message", 1); // Noncompliant - String contains no format specifiers. org.apache.logging.log4j.Logger log4jLog; log4jLog.debug("message", 1); // Noncompliant - String contains no format specifiers.
Compliant Solution
String.format("First %s and then %s", "foo", "bar"); String.format("Display %2$d and then %d", 1, 3); String.format("Too many arguments %d %d", 1, 2); String.format("First Line%n"); String.format("Is myObject null ? %b", myObject == null); String.format("value is %d", value); String s = "string without arguments"; MessageFormat.format("Result {0}.", value); MessageFormat.format("Result '{0}' = {0}", value); MessageFormat.format("Result {0}.", myObject); java.util.Logger logger; logger.log(java.util.logging.Level.SEVERE, "Result {0}.", myObject); logger.log(java.util.logging.Level.SEVERE, "Result {0}'", 14); logger.log(java.util.logging.Level.SEVERE, exception, () -> "Result " + param); org.slf4j.Logger slf4jLog; org.slf4j.Marker marker; slf4jLog.debug(marker, "message {}"); slf4jLog.debug(marker, "message {}", 1); org.apache.logging.log4j.Logger log4jLog; log4jLog.debug("message {}", 1);
See
- CERT, FIO47-C. - Use valid format strings
Invoke method(s) only conditionally. Use the built-in formatting to construct this argument. Open
logger.log(Level.FINEST, "Posting object: " + object.toString());
- Read upRead up
- 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.
Provide the parametrized type for this generic. Open
Map<String, Collection<Class>> reactionIdsToObjectTypeMap = new HashMap<>();
- Read upRead up
- Exclude checks
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;
Provide the parametrized type for this generic. Open
Class reactionClass = reaction.getClass();
- Read upRead up
- Exclude checks
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;
Use the built-in formatting to construct this argument. Open
logger.info("[reactionId=" + reactionId + "] does not match any of the registered reactions");
- Read upRead up
- 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.
Provide the parametrized type for this generic. Open
private void validateOnInputs(Class tClass, Consumer consumer, String reactionId) throws KaliumException {
- Read upRead up
- Exclude checks
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;
Format specifiers or lambda should be used instead of string concatenation. Open
logger.log(Level.FINEST, "Posting object: " + object.toString());
- Read upRead up
- Exclude checks
Because printf
-style format strings are interpreted at runtime, rather than validated by the compiler, they can contain errors that
result in the wrong strings being created. This rule statically validates the correlation of printf
-style format strings to their
arguments when calling the format(...)
methods of java.util.Formatter
, java.lang.String
,
java.io.PrintStream
, MessageFormat
, and java.io.PrintWriter
classes and the printf(...)
methods of
java.io.PrintStream
or java.io.PrintWriter
classes.
Noncompliant Code Example
String.format("First {0} and then {1}", "foo", "bar"); //Noncompliant. Looks like there is a confusion with the use of {{java.text.MessageFormat}}, parameters "foo" and "bar" will be simply ignored here String.format("Display %3$d and then %d", 1, 2, 3); //Noncompliant; the second argument '2' is unused String.format("Too many arguments %d and %d", 1, 2, 3); //Noncompliant; the third argument '3' is unused String.format("First Line\n"); //Noncompliant; %n should be used in place of \n to produce the platform-specific line separator String.format("Is myObject null ? %b", myObject); //Noncompliant; when a non-boolean argument is formatted with %b, it prints true for any nonnull value, and false for null. Even if intended, this is misleading. It's better to directly inject the boolean value (myObject == null in this case) String.format("value is " + value); // Noncompliant String s = String.format("string without arguments"); // Noncompliant MessageFormat.format("Result '{0}'.", value); // Noncompliant; String contains no format specifiers. (quote are discarding format specifiers) MessageFormat.format("Result {0}.", value, value); // Noncompliant; 2nd argument is not used MessageFormat.format("Result {0}.", myObject.toString()); // Noncompliant; no need to call toString() on objects java.util.Logger logger; logger.log(java.util.logging.Level.SEVERE, "Result {0}.", myObject.toString()); // Noncompliant; no need to call toString() on objects logger.log(java.util.logging.Level.SEVERE, "Result.", new Exception()); // compliant, parameter is an exception logger.log(java.util.logging.Level.SEVERE, "Result '{0}'", 14); // Noncompliant - String contains no format specifiers. logger.log(java.util.logging.Level.SEVERE, "Result " + param, exception); // Noncompliant; Lambda should be used to differ string concatenation. org.slf4j.Logger slf4jLog; org.slf4j.Marker marker; slf4jLog.debug(marker, "message {}"); slf4jLog.debug(marker, "message", 1); // Noncompliant - String contains no format specifiers. org.apache.logging.log4j.Logger log4jLog; log4jLog.debug("message", 1); // Noncompliant - String contains no format specifiers.
Compliant Solution
String.format("First %s and then %s", "foo", "bar"); String.format("Display %2$d and then %d", 1, 3); String.format("Too many arguments %d %d", 1, 2); String.format("First Line%n"); String.format("Is myObject null ? %b", myObject == null); String.format("value is %d", value); String s = "string without arguments"; MessageFormat.format("Result {0}.", value); MessageFormat.format("Result '{0}' = {0}", value); MessageFormat.format("Result {0}.", myObject); java.util.Logger logger; logger.log(java.util.logging.Level.SEVERE, "Result {0}.", myObject); logger.log(java.util.logging.Level.SEVERE, "Result {0}'", 14); logger.log(java.util.logging.Level.SEVERE, exception, () -> "Result " + param); org.slf4j.Logger slf4jLog; org.slf4j.Marker marker; slf4jLog.debug(marker, "message {}"); slf4jLog.debug(marker, "message {}", 1); org.apache.logging.log4j.Logger log4jLog; log4jLog.debug("message {}", 1);
See
- CERT, FIO47-C. - Use valid format strings
Provide the parametrized type for this generic. Open
private void validateOnInputs(Class tClass, Consumer consumer, String reactionId) throws KaliumException {
- Read upRead up
- Exclude checks
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;
Use the built-in formatting to construct this argument. Open
logger.info("Reaction in form of lambda expression was added. " +
"[class=" + tClass.getName() + "],[reactionId=" + reactionId + "]");
- Read upRead up
- 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.
Provide the parametrized type for this generic. Open
Map<Class, List<Method>> objectTypeToHandlersMap = new HashMap<>();
- Read upRead up
- Exclude checks
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;