24.3.12

Find potential nullpointer at compile time - JSR 305

Even though JSR 305 is inactive, it is nevertheless very useful and even more important, supported by tools like FindBugs. But first things first.

JSR 305 defines various annotations  for specifying meta information for methods, parameters etc. These information can than be used by tools to find potential problems or bugs.
Furthermore, it can be extremely useful for separated teams, where you often struggle with nullpointer exceptions. You simply cannot foresee what  a method will return without taking a look into its implementation or which DTO fields will be instantiated.
Additionally, as an implementer of a component it encourages you to spend some time thinking about the return values and the passed parameters.

So, if you want to include the Annotations into your project simply introduce the following maven dependency

    <dependency>
            <groupId>com.google.code.findbugs<Aft/groupId>
            <artifactId>jsr305</artifactId>
            <version>2.0.0</version>
        </dependency>

After that you can use the following annotations to specify e.g. your interface's method:
   
    @CheckForNull Integer doSomethingElse(@Nonnull Long id);
   
    @Nonnull Integer doSomething(@Nonnull Long id);
   
By just taking glancing over this interface you immediately get an idea of potential problems.

After that, you can use the FindBug Eclipse plugin to check your implementation or client classes.
FindBug found an error ,for the following implementation of  doSomething, as the method should not return null:

The following client code produced one error and one warning. The first method passes null and so FindBug marks it as an error. The second one does not check if the returned value is null and therefore produces a warning.





Furthermore, FindBug is part of Sonar and the found problems will thereby be part of the generated reports.


JSR 305 includes more Annotations than shown here, but if they should not be sufficient, you can use the following code to create your own.

@Documented
@TypeQualifier
@Retention(RetentionPolicy.RUNTIME)
public @interface SpecialAwesomeAnnotation {

}

JSR 305

Google Tech Talk

PS:

Give Ceylon a try if you want a language aware of nullpointers :)


No comments:

Post a Comment