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

Sonar issue: define a constant instead of copying this literal

WBOY
Release: 2024-02-10 08:15:08
forward
1042 people have browsed it

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);
Copy after login

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);
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template