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:
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! }
There are many ways to express the contract:
@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.Option<T>
or NotNull<T>
, which add clarity and at least runtime checking.if(doSomething() != null){ Object object = doSomething(); From a performance perspective this method is being asked to run twice, once to check it doesn't return null and next to assign the new variable as long as it returns a valid object.
You could change the method return type to return java. lang. Integer and then you can return null, and existing code that returns int will get autoboxed. Nulls are assigned only to reference types, it means the reference doesn't point to anything.
To check if it is null, we call the isNull() method and pass the object getUserObject as a parameter. It returns true as the passed object is null.
Returning Null is Bad Practice The FirstOrDefault method silently returns null if no order is found in the database. There are a couple of problems here: Callers of GetOrder method must implement null reference checking to avoid getting a NullReferenceException when accessing Order class members.
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! }
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With