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
@NotNullbecause 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>orNotNull<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.
A very good follow up question. I consider
nulla truly special value, and if a method may returnnullit 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 returnnullunless 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.