Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show if a method may return null

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.
like image 668
Lena Schimmel Avatar asked Jan 04 '09 18:01

Lena Schimmel


People also ask

How check a method returns null in Java?

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.

Can a method return null?

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.

How do you check if a function is null?

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.

Is it good to return null in Java?

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.


2 Answers

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! } 
like image 86
Ronald Blaschke Avatar answered Sep 24 '22 21:09

Ronald Blaschke


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) 
like image 41
Apocalisp Avatar answered Sep 21 '22 21:09

Apocalisp