1. 程式人生 > >One More Recipe Against NULL

One More Recipe Against NULL

You know what NULL is, right? It’s evil. In OOP, your method can return NULL, it can accept NULL as an argument, your object can encapsulate it as an attribute, or you can assign it to a variable. All four scenarios are bad for the maintainability of your code—there are no doubts about that. The question is what to do instead. Let’s discuss the “return it” part and I will suggest one more “best practice” on top of what

was discussed a few years ago.

Snatch (2000) by Guy Ritchie
Snatch (2000) by Guy Ritchie

Look at this code:

Integer max(List<Integer> items) {
  // Calculate the maximum of all
  // items and return it.
}

What should this method do if the list is empty? Java’s Collections.max() throws an exception. Ruby’s Enumerable.max() returns nil

. PHP’s max() returns FALSE. Python’s max() raises an exception. C#’s Enumerable.Max() also throws an exception. JavaScript’s Math.max() returns NaN.

Which is the right way, huh? An exception, NULL, false or NaN?

An exception, if you ask me.

But there is yet another approach, which is better than an exception. This one:

Integer max(List<Integer> items, Integer def) {
  // Calculate the maximum of all
  // items and return it. Returns 'def' if the
  // list is empty.
}

The “default” object will be returned if the list is empty. This feature is implemented in Python’s max() function: it’s possible to pass both a list and a default element to return in case the list is empty. If the default element is not provided, the exception will be raised.