How to show if a method may return null
Asked Answered
D

11

55

After posting this question and reading that one I realized that it is very important to know if a method is supposed to return null, or if this is considered an error condition and an exceptions should be thrown. There also is a nice discussion when to return ‘null’ or throw exception .

I'm writing a method and I already know if I want to return null or throw an exception, what is the best way to express my decision, in other words, to document my contract?

Some ways I can think of:

  • Write it down in the specs / the documentation (will anyone read it?)
  • Make it part of the method name (as I suggested here)
  • assume that every method that throws an exception will not return null, and every one that does 'not' throw might return null.

I'm mainly talking about java, but it might apply to other languages, too: Why is there a formal way to express if exceptions will be thrown (the throws keywords) but no formal way to express if null might be returned?

Why isn't there something like that:

public notnull Object methodWhichCannotReturnNull(int i) throws Exception
{
    return null; // this would lead to a compiler error!
}

Summary and Conclusion

There are many ways to express the contract:

  • If your IDE supports it (as IntelliJ), it's best to use an annotation like @NotNull because it is visible to the programmer and can be used for automated compile time checking. There's a plugin for Eclipse to add support for these, but it didn't work for me.
  • If these are not an option, use custom Types like Option<T> or NotNull<T>, which add clarity and at least runtime checking.
  • In any way, documenting the contract in the JavaDoc never hurts and sometimes even helps.
  • Using method names to document the nullability of the return value was not proposed by anyone but me, and though it might be very verbose und not always useful, I still believe sometimes it has its advantages, too.
Dissatisfied answered 4/1, 2009 at 18:30 Comment(1)
related: #4963800Wolfram
O
41

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!
}
Ogham answered 4/1, 2009 at 18:53 Comment(5)
Good answer: writing it explicitly in the javadoc is something I like to see (as explained in stackoverflow.com/questions/61604). However, I rarely see any complete javadoc from my colleagues. Sometimes, I do not see any javadoc at all, because the "code is a documentation in itself"...arghFlaherty
For what it's worth, if you have FindBugs in your build chain, it supports checking @NonNull and similar hints right now.Copolymerize
The JSR seems to be in Progress for some time now, actually since 2006... is it usual to take so long for such a small change?Dissatisfied
It may well be that people realized that the scope of the JSR is too narrow, and left it to be handled by tools. Seems like this is now a feature of JSR 308: Annotations on Java Types.Ogham
If this was unclear to anybody, JSR 308: "The specific annotation names, such as @NonNull, are examples only; this document does not propose any annotations, merely specifying where they can appear in Java code."Parol
F
10

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)
Felafel answered 4/1, 2009 at 18:45 Comment(5)
Sounds very interesting. But I will have to think about it for a while to know if it's really helpfull.Dissatisfied
Just an addition, Java 1.8 now has the Optional class which does the same thing as Option from Guava.Orlon
Java 1.8 now has a minimally useful Optional class, 6 years later.Felafel
The Optional class is one of the most profoundly idiotic additions to Java I've ever heard of. Such a useful programming feature was implemented so terribly, that its only accomplishment was replacing NullPointerException with NoSuchElementException.Dermal
I like the idea of this approach but only on new projects. Refactoring existing code that uses null to use this instead would be a nightmare.Polychrome
N
2

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.

Nosewheel answered 4/1, 2009 at 18:51 Comment(0)
P
2

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:

  1. wait for language support to express it (e.g. the C# ?! thing)
  2. use Aspect Orientation to build your own language extensions to express it
  3. use a custom type to express it
  4. (but builds on developer cooperation) use a naming scheme to indicate it
Pathfinder answered 4/1, 2009 at 18:53 Comment(0)
R
2

For Java, one can use the Javadoc description of a method to document the meaning of the returned value, including whether it can be null. As has been mentioned, annotations may also provide assistance here.

On the other hand, I admit that I don't see null as something to be feared. There are situations in which "nobody's home" is a meaningful condition (although the Null Object technique also has real value here).

It is certainly true that attempting a method invocation on a null value will cause an exception. But so will attempting to divide by zero. That doesn't mean that we need to go on a campaign to eliminate zeroes! It just means that we need to understand the contract on a method and do the right thing with the values that it returns.

Ramey answered 4/1, 2009 at 20:43 Comment(1)
But, you can't "understand the contract" if it doesn't explicitly mention null. It is not something to be feared, but it needs to be checked for if it is a valid return type, something the contract should explicitly state as in rblasch's answer. Code is cleaner without lots of checks for null.Rostrum
A
2

At all costs, avoid relying on the JavaDocs. People only read them if the signature doesn't appear trivial and self-explanatory (Which is bad to begin with), and these who actually bother to read them are less likely to make a mistake with the nulls since they are currently being more careful.

Accidental answered 4/1, 2009 at 20:48 Comment(1)
Plus the JavaDoc might be inaccurate, e.g out of date.Hallucinogen
C
1

Have you had a look at Spec#?

Cullum answered 4/1, 2009 at 18:36 Comment(3)
Didn't know that. Looks interesting, but I'm always sceptical when it comes to using derivatives of programming languages. I would rather like such a feature in the official language core. But I will have a look at it.Dissatisfied
Hi Brian. This is a research project by Microsoft and could/might be included in future versions of C#.Cullum
@LenaSchimmel if you want non-nullability as a feature of non-derived language, you should look at Kotlin.Unsure
C
1

You could write your own annotation (Java) or attribute (C#) to indicate that the return value might be null. Nothing will automatically check it (although .NET 4.0 will have code contracts for this sort of thing) but it would at least act as documentation.

Chanson answered 4/1, 2009 at 18:43 Comment(0)
L
1

Maybe you could define a generic class named "NotNull", so that your method might be like:

public NotNull<Object> methodWhichCannotReturnNull(int i) throws Exception
{
   // the following would lead to a run-time error thown by the
   // NotNull constructor, if it's constructed with a null value
   return new NotNull<Object>(null);
}

This is still a run-time (not a compile-time) check, but:

  • It's thrown in the implementation of the method (it's not a fault in the calling code)
  • It's self-documenting (the caller knows he's geting NotNull<T> as a return type)
Lake answered 4/1, 2009 at 18:58 Comment(1)
This puts the null check in one place, but it's still a runtime check.Felafel
B
0

If you're using Java 5+, you can use a custom Annotation, e.g. @MayReturnNull

UPDATE

All coding philosophy aside (returning null, using exceptions, assertions, yada yada), I hope the above answers your question. Apart from primitives having default values, complex types may or may not be null, and your code needs to deal with it.

Bushman answered 4/1, 2009 at 18:45 Comment(0)
T
0

Generally speaking, I would assume that a null return value is against the contract of the API by default. It is almost always possible to design your code such that a null value is never returned from your APIs during "normal" flow of execution. (For example, check foo.contains(obj) rather then calling foo.get(obj) and having a separate branch for null. Or, use the Null object pattern.

If you cannot design your API in such a way, I would clearly document when and why a null could be thrown--at least in the Javadoc, and possibly also using a custom @annotation such as several of the other answers have suggested.

Titoism answered 4/1, 2009 at 19:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.