Explain Codes LogoExplain Codes Logo

Turning Sonar off for certain code

java
sonarqube
suppression
annotations
Nikita BarsukovbyNikita Barsukov·Sep 5, 2024
TLDR

Hush SonarLint/SonarQube up for specific code by using @SuppressWarnings("squid:RuleID") for whole classes/methods, or //NOSONAR for single-line critiques.

// Mute a specific party-pooper rule for a method/class @SuppressWarnings("squid:1234") // Rule no.1234: Friends don't let friends write lousy code! public void method() { //... code here } // Turn a blind eye to this line int var = 0; //NOSONAR, Nobody move! I lost an unused variable.

Locate and annihilate

To silence warnings, you need the SonarQube rule ID. Open up the SonarQube UI, go to Issues Drilldown, find your pesky issue, and click on the Rule link. The rule ID is right at the top, something like squid:S00112. Behold, your suppressant!

Non-specific silencers

When using @SuppressWarnings feels like using a sledgehammer to swat a fly, call //NOSONAR into action to exclude a single line. This shotgun approach is less elegant than @SuppressWarnings, so remember, with great power comes great responsibility!

Annotations for the rescue

Deploy the @SuppressFBWarnings annotation not just to fool Sonar, but also to explain why. Part of the FindBugs migration agreement, it still works the same magic!

@SuppressFBWarnings(value = "ID", justification = "Just standing my ground")

For excluding the big guns

Does your project have more modules than you can count on your fingers? When annotations can't keep up, configure Sonar's analysis scope to exclude entire files or directories. This keeps your codebase neat as a pin and Sonar focused on the real McCoy.

# In sonar-project.properties sonar.exclusions=**/gen/**/*,**/*Mock*.java

The art of clean exclusions

Scope it right

Strike a balance. Broad exclusions are a recipe for missing potential flaws while targeted suppressions protect the quality of your codebase.

Periodic checks

Out of sight, out of mind? Not quite. Keep a close eye on suppressed warnings as their relevance may change over time.

CI/CD eats this for breakfast

In CI pipelines, exclude generated code or third-party libraries to focus on the greatness of your original code.

Gotchas ahead

Too much of //NOSONAR

You wouldn't want to hide flaws under the carpet. Too many //NOSONAR can create a fantasyland of flawless code.

Justify your suppressions

Omit the excuses at your peril. Suppressing without justifying makes your future code maintenance a journey into the labyrinth.

Quality gates and profiles stay

Suppressing does not pull the plugs on quality gates. The suppressed issues can still impact your project's status in the SonarQube Quality Gate if not reflected in the quality profile configuration.