Skip to Content
Author's profile photo Robinson Selvamani

How To Avoid Sonar Violations

Compromising with quality will slow down productivity.  So continuous evaluation is required to check the quality of the code. Sonar does this. Sonar is a java based open source platform that evaluates and reports on source code quality. Sonar also helps Continuous Integration process. Sonar has a set of rules violating which will fail the  build.

Here are some Do’s and Dont’s that will help the developer in avoiding sonar violations.

1. Do not throw Raw Exception Types

     Instead of throwing raw exception types such as Exception, Throwable or Error, throw specific exceptions.

2. Do not use deprecated methods

3. Do not use == or != operators for string comparison

     The operators == and != are used for comparing java.lang.String objects for reference equality.  Unless both strings are constants or have been interned using the String.intern() method, use equals(Object) method instead.

4. Do not throw exception in finally block

     Sonar treat this violation as very severe one.

5. Do not have empty catch block

       Empty catch block nullify the effect of throwing exception. Log the exception properly or do some relevant operations in the catch block.

6. Do not have empty finally Block

     Empty finally blocks are useless.

7. Use braces in If-else and for statements.

     Braces make the code highly readable.

8. Do not catch java.lang.Exception, java.lang.Error or java.lang.RuntimeException.

     Catch the specific exceptions.

9. Do not declare Throws Exception  in method signature

     Throw specific exceptions.

10. Do not write System.out.print

     Log the information instead of using System.out.print or System.out.println statement.

11. Follow naming conventions


     Class names should always begin with an upper case letter and method name should begin with lower case letter.

12. Do not rethrow exception in catch block

     Catch blocks that merely rethrow a caught exception only increase the code size and run-time complexity.

13. Avoid empty if blocks.



      if ( == Dialog.OK) {   


14. Do null check wherever required.

15. Do not use fall through in switch-case statements especially when the case is not empty.


      Create a method and call them in the fall through case  to avoid code duplication.

16. Avoid duplicate condition in if-else statement:


     if (item == null && count == 1) {

     //do something

     } else if (item == null && count> 1) {

     //do something


    The duplicate condition, item == null, can be avoided by having a nested if statement as shown below.

     if (item == null) {

          if(count == 1) {

          //do something

          } else if (count> 1) {

          //do something



Assigned Tags

      Be the first to leave a comment
      You must be Logged on to comment or reply to a post.