SonarQube: Invoke method(s) only conditionally

Olezt picture Olezt · Jun 2, 2017 · Viewed 24.1k times · Source

The following part of code raises a major bug at SonarQube : "Invoke method(s) only conditionally."
How am I supposed to fix this?

if(us != null){
    logger.info("Log this: {}", us.toString());
}

Answer

Tibor Blenessy picture Tibor Blenessy · Jun 2, 2017

The call to us.toString() is redundant, toString() method will be called regardless the configured log level. You should pass only us as an argument to info without an if statement.

logger.info("Log this: {}", us);