javasonarqubesonarlint

Sonar issue: define a constant instead of duplicating this literal


I am having the below log line in a java file 3 times in my project==

   log.info(
                    "Queuing workflow message with ID {} and shardedDatabaseId {}",
                    workflowQueueMessageString,
                    shardedDatabaseId);

This is generating a critical issue by sonar==

Define a constant instead of duplicating this literal "Queuing workflow message with ID {} and shardId {}" 3 times.

I can understand the reason for this error. But the string is actually not a constant and has placeholders like {}. So how to correctly address this Sonar reported issue.


Solution

  • This string is the format of the log message. Even if the message itself is not constant, the format is constant.

    Just declare it (the format) as a variable - final, static, whatever is applicable to the use case.

    String messageFormat = "Queuing workflow message with ID {} and shardedDatabaseId {}";
    log.info(messageFormat, workflowQueueMessageString, shardedDatabaseId);
    ...
    log.info(messageFormat, workflowQueueMessageString, shardedDatabaseId);
    ...
    log.info(messageFormat, workflowQueueMessageString, shardedDatabaseId);