What To Return

What To Return

Photo by Clément H on Unsplash

 

Today I wanted to publish an article on why we should often prefer Aggregation over Inheritance, but I didn’t get it to a point where I was happy with it. I’ll release it next week instead. Sorry about any inconvenience.

OK, let’s crack into today’s topic.

Say, we have a method GetCustomer(customerId). What would we expect it to return? Well, a Customer instance, obviously. What if it didn’t find a customer for the customerId argument? In that case, I think, most developers would expect a null value. A null nicely communicates ‘nothing found, nada’. 

So far, so good.

What about if we had a method that returned several values, a collection?

What should SearchCustomers(criteria) return? It ought to return a collection of values. Correct. 

OK, what if SearchCustomers() didn’t find any matching values? Should it return a null value? That would be nicely consistent with the singular case. Or should it return an empty collection?

A tricky question, right?

Let’s examine the null case:

  • Clients will need to check for null values. Or risk the possibility of the dreaded NullReferenceException (.NET) or NullPointerException (Java).
  • We have two distinct scenarios communicating ’empty collection’ to callers: null value, and an actual empty collection. Ambiguity is not good. It’s better to be clear about what things mean.

And the case of the empty collection:

  • The return value is always a collection. It may or may not have values in it. As a developer, it’s nice to work with such consistency.
  • Since clients are guaranteed to get a collection, they may call methods on the collection without safety null-checks, simplifying the code. 

It looks like we have a winner! 

Returning a collection when the client expects a collection is a programming hygiene factor. On the other hand, if we are less careful and hand the caller a null collection, we must be aware that we could break them. And that is not something responsible developers do, right?

So, when there are no values to return for a collection, please pass back an empty collection, not a null.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply