Topic: Using FindBugs in Tooltwist
FindBugs is an eclipse plugin that reviews code and checks for common java coding errors. The errors range from un-removed "TODO" comments; to inefficiency in the code; to possible masking of potential bugs.
To install FindBugs:
1. Click on Help > Install New Software...
2. Click on Add...
3. Fill in the following:
- Name: FindBugs
- Location: http://findbugs.cs.umd.edu/eclipse/
4. Check FindBugs and the packages underneath it
5. Continue the installation process by clicking on Next, I Agree, etc..
To use FindBugs
1. Right-Click on the project
2. Select Find Bugs > Find Bugs
3. The Find Bugs perspective gives a list of possible bugs with suggestions
Here's a list of common bugs found by Find Bugs on the Tutuki project and suggested actions:
1. When concatinating strings, especially within a loop, use StringBuffer instead of String
wrong way:
String s = "----\n";
for (int i = 0; i < 10; i++) {
s += "hello\n";
}
System.out.println(s); correct way:
StringBuffer s = new StringBuffer("----\n");
for (int i = 0; i < 10; i++) {
s.append("hello\n");
}
System.out.println(s.toString()); note: StringBuffer does not override the equals(Object) method. Use the equals method of String by:
StringBuffer sb = new StringBuffer("hello");
if ("hello".equals(sb.toString())) ... or:
if (sb.toString().equals("hello")) ...2. Avoid empty catch blocks
wrong way:
catch (Exception ex) {} note: at the very least, do an ex.printStackTrace(); This is still not recommended though. Best is to re-raise an exception. Let tooltwist/tomcat/java handle that for you.
best way:
catch (Exception ex) {
// few handling/logging statements
throw new CustomException(ex);
}3. Handle specific exceptions explicitly.
wrong way:
catch (Exception ex) right way:
catch (ExType1 ex) {
...
}
catch (ExType2 ex) {
...
}According to FindBugs: "this construct also accidentally catches RuntimeException as well, masking potential bugs."
4. When a variable is not in use, delete it. If you think the code will use this later, just comment it out. The bulk of the errors/warnings was because of advance code. One particular sample is the log4j logger.
5. Misc:
- Always remove autogenerated comments. These are comments marked with the text 'TODO Auto-generated'.
- Always remove unused imports. An eclipse shortcut is to press Command-Shift-'O' to organize imports.
