How to show if a method may return null
Solution 1:
A very good follow up question. I consider null
a truly special value, and if a method may return null
it must clearly document in the Javadoc when it does (@return some value ..., or null if ...
). When coding I'm defensive, and assume a method may return null
unless I'm convinced it can't (e.g., because the Javadoc said so.)
People realized that this is an issue, and a proposed solution is to use annotations to state the intention in a way it can be checked automatically. See JSR 305: Annotations for Software Defect Detection, JSR 308: Annotations on Java Types and JetBrain's Nullable How-To.
Your example might look like this, and refused by the IDE, the compiler or other code analysis tools.
@NotNull
public Object methodWhichCannotReturnNull(int i) throws Exception
{
return null; // this would lead to a compiler error!
}
Solution 2:
You can use the Option
type, which is very much like a list that has zero or one element. A return type of Option<Object>
indicates that the method may return an Object
, or it may return a special value of type None
. This type is a replacement for the use of null with better type checks.
Example:
public Option<Integer> parseInt(String s) {
try {
return Option.some(Integer.parseInt(s));
}
catch (Exception e) {
return Option.none();
}
}
If you use this consistently, you can turn on IDE null-warnings, or just use grep for null
which should not appear in your code at all if you use Option.none()
everywhere you would normaly use a null
literal.
Option
comes standard with Scala, and it is called Maybe
in Haskell. The link above is to a library called Functional Java that includes it. That version implements the Iterable
interface, and has monadic methods that let you compose things nicely. For example, to provide a default value of 0 in case of None
:
int x = optionalInt.orSome(0);
And you can replace this...
if (myString != null && !"".equals(myString))
...with this, if you have an Option<String>
...
for (String s : myOptionString)
Solution 3:
There's some support for a @Nullable and @NotNull annotation in IntelliJ IDEA. There's also some talk about adding those annotations (or a similar feature) to Java 7. Unfortunately I don't know how far that got or if it's still on track at all.
Solution 4:
Indeed: in our framework we have a 'non-null' pointer type, which may be returned to indicate that the method will always return a value.
I see three options:
- wait for language support to express it (e.g. the C# ?! thing)
- use Aspect Orientation to build your own language extensions to express it
- use a custom type to express it
- (but builds on developer cooperation) use a naming scheme to indicate it