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.
Example:
if (dialog.open() == 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:
Example:
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
}
}
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
User | Count |
---|---|
29 | |
21 | |
10 | |
7 | |
7 | |
6 | |
6 | |
5 | |
5 | |
5 |