In almost all projects of mine I got used to a utility class called Default. Default would provide static methods, whereas each method comes with a single parameter. The purpose of Default was nothing more than to provide default values if the argument is null at runtime.
Doin it the Groovy way
With the upcoming popularity of Groovy AST transformations, I thought it would be time to write a small NullSafeASTTransformation with the attached @NullSafe annotation.
As Groovy is dynamically typed, @NullSafe is restricted to work on statically declared local variables.
As you can see in the code sample above, @NullSafe ensures that the according variable value is at least of the variables type's default value, after the initial expression has been executed at runtime.
In addition, the NullSafeASTTransformation checks all variable assignments with a custom class code visitor, to ensure that a variable assignment will result in the default value and not null.
The NullSafeASTTransformation is a local AST transformation , injecting static method calls to a hidden NullSafeUtil class:
The most important points besides checking if the annotation has been applied in a valid context, is the injection of the static method call to NullSafeUtil.nullSafe. As Groovy dynamically dispatches static method calls it is ensured that static method selection is based on the variables runtime type.
The @NullSafe annotation currently works on statically typed local variables. At time of writing, the types cover all Number descendants, String and Character.
You can have a look at the complete source at Github , please contribute or leave comments!