SonarLint: Invoke method(s) only conditionally

SonarLink invoke method conditionally

If you are using IntelliJ and are using the SonarLint linting plugin, then you may have come across the error:

SonarLint: Invoke method(s) only conditionally

Contents

Problem

This error is often caused when using a logger coupled with the String.format method like this:

The reason for this is that the logger itself will be formatting the string. So using String.format inside the logger call is unnecessary and will incur a performance hit.

Solution

The solution is to let the logger handle the string formatting.

So the erring code can be changed from:

logger.info(String.format("my message %s", message));

to:

logger.info("my message {}", message));

This offloads the handling of the string formatting to the logger and you will no longer get the SonarLint error.

Hope that helps!

If you have any questions or problems leave a comment in the comments section below.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.