Thursday, August 24, 2006

More on Nullness

WARNING: This blog entry was imported from my old blog on blogs.sun.com (which used different blogging software), so formatting and links may not be correct.


The other day I
wrote about using annotations to state your intent regarding null for fields, parameters and return values. This can help static checkers like
findbugs find flaws in your code, where you fail to check return values for null where that is known to be risky. (In fact, findbugs does not only base knowledge of nullness on your use of annotations; it also has a builtin database of system API null behaviors, since these classes have not been "instrumented" with nullness annotations yet.)



I did however mention one big problem: These annotations are not (yet) standard - so you'll need to choose to use them from somewhere - and add third party imports to all your source files, add a foreign jar to your build, etc. Findbugs' set of annotations is probably as good a candidate as any. But while the annotations are licensed under LGPL, which should be fine for most of us, some companies (or at least their lawyers) are weary of mixing GPL anything with proprietary code.



Our lawyers are generally fine with LGPL usage, but I was still wondering if there was a way I could "isolate" myself by using an annotation from my own project, and then somehow tie that to a standard annotation in a single place. If annotations were like classes this would be easy - I could simply extend the findbugs one and I'd be done. But annotations don't work that way. So I thought I'd take a look at findbugs internals and see what's going on.



And I was surprised, and happily surprised at that, to discover that findbugs is very tolerant in how it deals with nullability annotations. It is not favoring its own annotations. In fact, all it checks for is whether the annotation base name matches the name findbugs has chosen. This was probably done deliberately, to ensure that findbugs works with code annotated for other tools, such as IntelliJ. This is really a great idea - and it doesn't seem risky to me; I can't think of many other uses for an annotation named "CheckForNull" or "NonNull". Of course, if a problem ever arises they can always update findbugs to be more discriminating for users who want to use home grown annotations where those names mean something else.



So, you can simply define your own project wide nullability annotations (they are simple marker annotations with no members), and then findbugs will happily do its magic. Worked like a charm for me:






Null Handling: Much ado about nothing, literally.



P.S. For more about the built-in set of null knowledge of Java standard APIs, see the class NullnessAnnotationDatabase in the findbugs source distribution (which handily comes distributed as a NetBeans ant-based project - thanks!)


1 comment:

  1. You might want to take a look at
    http://jcp.org/en/jsr/detail?id=305

    ReplyDelete