I want to address the necessity to test every object if you want to access a field or method of this object.
For example:
[code]
if (someobject != null) {
someobject.doCalc();
}
[/code]
In this case I will avoid a NullPointerException, and I don’t know exactly if the object is null or not. These tests appear throughout my code as a consequence.
Is there a good alternative to this?
If you use (or planning to use) JetBrains IntelliJ IDEA, a Java IDE, you can use some particular annotations developed by them.
Basically, you’ve got @Nullable and @NotNull.
You can use in method and parameters, like this:
[code]
@NotNull public static String helloWorld() {
return “Hello World”;
}
[/code]
or
[code]
@Nullable public static String helloWorld() {
return “Hello World”;
}
[/code]
The second example won’t compile (in IntelliJ IDEA).
When you use the first helloWorld() function in another piece of code:
[code]
public static void main(String[] args)
{
String result = helloWorld();
if(result != null) {
System.out.println(result);
}
}
[/code]
Now the IntelliJ IDEA compiler will tell you that the check is useless, since the helloWorld() function won’t return null, ever.
Using parameter
[code]
void someMethod(@NotNull someParameter) { }
[/code]
if you write something like:
[code]
someMethod(null);
[/code]
This won’t compile.
Last example using @Nullable
[code]
@Nullable iWantToDestroyEverything() { return null; }
[/code]
Doing this
[code]
iWantToDestroyEverything().something();
[/code]
And you can be sure that this won’t happen. 🙂
It’s a nice way to let the compiler check something more than it usually does and to enforce your contracts to be stronger. Unfortunately, it’s not supported by all the compilers.
In IntelliJ IDEA 10.5 and on, they added support for any other @Nullable @NotNull implementations.
See blog post More flexible and configurable @Nullable/@NotNull annotations.