All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.l10n.java.rules.java.S3457.html Maven / Gradle / Ivy

Why is this an issue?

A printf--style format string is a string that contains placeholders, usually represented by special characters such as "%s" or "{}", depending on the technology in use. These placeholders are replaced by values when the string is printed or logged.

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 checks whether every format string specifier can be correctly matched with one of the additional arguments when calling the following methods:

How to fix it

A printf--style format string is a string that contains placeholders, which are replaced by values when the string is printed or logged. Mismatch in the format specifiers and the arguments provided can lead to incorrect strings being created.

To avoid issues, a developer should ensure that the provided arguments match format specifiers.

Note that MessageFormat is used by most logging mechanisms, for example java.util.logging.Logger, thus the single quote must be escaped by a double single quote.

Code examples

Noncompliant code example

void logging(org.slf4j.Logger slf4jLog, java.util.logging.Logger logger) {
    String.format("Too many arguments %d and %d", 1, 2, 3); // Noncompliant - the third argument '3' is unused
    String.format("First {0} and then {1}", "foo", "bar");  //Noncompliant - it appears there is confusion with the use of "java.text.MessageFormat" - parameters "foo" and "bar" will be ignored here


    slf4jLog.debug("The number: ", 1); // Noncompliant - String contains no format specifiers.

    logger.log(level, "Can't load library \"{0}\"!", "foo"); // Noncompliant - the single quote ' must be escaped
}

Compliant solution

void logging(org.slf4j.Logger slf4jLog, java.util.logging.Logger logger) {
    String.format("Too many arguments %d and %d", 1, 2);
    String.format("First %s and then %s", "foo", "bar");

    slf4jLog.debug("The number: {}", 1);

    logger.log(level, "Can''t load library \"{0}\"!", "foo");
}

Resources





© 2015 - 2025 Weber Informatics LLC | Privacy Policy