# SonarLint check tips and solutions

SonarLint inspection tips and solutions


SonarLint: Use the built-in formatting to construct this argument.
  • Translation: Passing the connection string to the logging method may also cause unnecessary performance loss, because the connection will be performed every time the method is called, regardless of whether the log level is low enough to display the message. The built-in string format should be used instead of string concatenation. If the message is the result of a method call, the preconditions should be skipped completely, and related exceptions should be thrown conditionally.

  • Counterexample

String message = "Hellow World!";
logger.info("Test Info message:"+message);
  • Positive example
String message = "Hellow World!";
String format = String.format("Test Info message:%s", message);
logger.info(format);

SonarLint: Replace this use of System.out or System.err by a logger.
  • Translation: Use a dedicated logging framework to manipulate logs
  • Counterexample
System.out.printf("Hellow");
  • Positive example
private static final Logger logger = Logger.getLogger(String.valueOf(Demo.class));
logger.info("Hellow");

SonarLint: Invoke method(s) only conditionally.
  • Translation: Build code to pass static or pre-calculated values ​​to preconditions, condition checks, and record calls. The parameter in the method is directly the result after calculation, rather than calculating and getting the result.
  • Counterexample
logger.info(String.valueOf((char)c));
  • Positive example
String s2 = String.valueOf((char) c);
logger.info(s2);

SonarLint: Define and throw a dedicated exception instead of using a generic one.
  • Translation: Use your own defined exception class to throw exceptions, etc., do not use the original Exception, etc.
  • Counterexample
throw new Exception("Test");
  • Positive example
public class MyException extends RuntimeException{
    
    

    public MyException() {
    
    
    }

    public MyException(String message) {
    
    
        super(message);
    }
}

throw new MyException("Hellow");

SonarLint: String contains no format specifiers.
  • Translation: The string does not contain format specifiers.
  • Counterexample
String message = "Hellow Test!";
logger.info(String.format("method error: {}",message));
  • Positive example
String message = "Hellow Test!";
logger.info(String.format("method error: %s",message));

Guess you like

Origin blog.csdn.net/qq_37248504/article/details/115264232