Home  >  Article  >  Sonar issue: define a constant instead of copying this literal

Sonar issue: define a constant instead of copying this literal

WBOY
WBOYforward
2024-02-10 08:15:081002browse

Sonar problem has always been one of the problems that programmers often encounter in PHP development. When working with text, many developers are used to copying and pasting text, but there are some potential problems with doing so. PHP editor Xiaoxin suggests that in order to avoid these problems, it is best to define the text that needs to be reused as a constant. This will not only improve the maintainability of the code, but also reduce the possibility of errors and improve the quality of the code. In this article, we will discuss the sonar issue in detail and provide some solutions to help developers better deal with this problem.

Question content

The java file in my project has the following log line 3 times==

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

This creates a serious problem for sonar==

Define a constant instead of repeating this text "Queue workflow message using id {} and shardid {}" 3 times.

I can understand the reason for this error. But the string is not actually a constant and has placeholders like {}. So how to correctly resolve this sonar reporting 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 suits 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);

The above is the detailed content of Sonar issue: define a constant instead of copying this literal. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete