Static code analysis is a quick and easy way to automatically scan code for potential problems and improvements. The Eclipse compiler has some code analysis features. The latest milestone release (3.2 M5) contains a new feature: the null reference check. The null reference check can be enabled at the Java compiler options (disabled by default) and flags situations where a NullPointerException may occur. This is very useful! NullPointerExceptions are pretty serious bugs, and usually the null reference check spots other faults in the code logic as well. Let’s see some examples:
First an easy one to get started. The foo method will always fail because bar is null. This error will always show up in any (unit) test with a nasty stack trace, and it is pretty obvious in the code that this is wrong.
Lets do another one:
This is a bit more interesting: either nothing happens(when bar is not null), or it crashes. The logic in the if-condition seems flawed: bar should NOT be null. Probably this is the intended behavior:
That’s a lot better. Eclipse stops complaining, and the code actually works now.
Let’s turn the previous examples around and see what happens:
This is more subtle: the line above the if statement only executes properly when bar is not null. The if-condition is either unnecessary or the check for not-null is at the wrong spot. This code will work as long as bar is not null though, so
in your initial test-run this problem might not be detected; in essence that makes this a potentially more evil bug than the ones above.
One last situation for the Eclipse null-reference check:
Similar to the problem above, this code will work as long as bar is not null. When bar is null, the method intends to print an error, but it should
prevent the execution of the bar.toUpperCase() as well. Again a more subtle bug, you’ll be happy Eclipse catches them for you. 🙂
The Eclipse null-reference analysis spots real and sometimes hard to find bugs in your code. Not ready to use Eclipse 3.2 M5 yet? Try the FindBugs plug-in or stand-alone analysis tools. Their latest version (0.9.5) actually works again when using it on larger projects, and has several other interesting static analysis checks to improve your code.