November 25, 2005

IntelliJ IDEA 6.0 "Demetra": Runtime assertions for @NotNull

One of the recently implemented features which I’m personally quite happy to see in the product is the possibility to automatically verify @NotNull annotations at runtime.

To give some background, IntelliJ IDEA 5.0 introduced annotations @Nullable and @NotNull which can be used to mark variables, fields, method parameters and return values which may be null (@Nullable) or may never be null (@NotNull). The annotations are clearly useful as documentation (which is quite significant by itself), but the more important thing is that IntelliJ IDEA 5.0 uses them to highlight places where a null pointer exception could occur. If the “Constant conditions and exceptions” inspection is enabled, places where a possibly null value is dereferenced are highlighted as warnings.

Now, this is good but not great. IntelliJ IDEA has a lot of inspections and usually highlights many warnings, and not all of them are promptly resolved. We always wanted to augment the design-time analysis with run-time checks, so that a violation of the @NotNull contract would be clearly reported as soon as it is detected, and not manifest as an NPE several layers deeper in the code. And Demetra provides just that.

If the option “Add @NotNull assertions” is enabled, IDEA instruments the bytecode of compiled classes and adds assertions checking that null values are not passed to @NotNull method parameters, and not returned from methods annotated as @NotNull.

The following screenshot shows a real example of a bug in the InspectionGadgets plugin that we discovered through the @NotNull assertions. (Note that IntelliJ IDEA highlights a possible NPE because the PsiForStatement.getBody() method is annotated as @Nullable.)

The runtime assertions will be of most immediate use to our plugin developers. A significant part of our OpenAPI is annotated with @Nullable and @NotNull, and many plugin programming errors should now be reported much more clearly than before.

(Speaking of plugin developers, today we launched a new plugins page on the IDEA Web site. Hopefully the plugin development information will now be much easier to find.)

Posted by Dmitry Jemerov at November 25, 2005 10:00 PM

The assertion code is only added when the source is compiled with IDEA but we are using Ant as a build tool. Is is possible to somehow use this feature from Ant as well?

Posted by: Jan-Erik at January 17, 2007 12:53 PM

The distribution of IntelliJ IDEA includes an Ant task (javac2.jar) which allows you to use @NotNull instrumentation if you build a project with Ant.

Posted by: Dmitry Jemerov at January 17, 2007 12:58 PM
Post a comment

Remember personal info?