Software Development

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

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.

Published on Java Code Geeks with permission by Yegor Bugayenko, partner at our JCG program. See the original article here: One More Recipe Against NULL

Opinions expressed by Java Code Geeks contributors are their own.

Yegor Bugayenko

Yegor Bugayenko is an Oracle certified Java architect, CEO of Zerocracy, author of Elegant Objects book series about object-oriented programing, lead architect and founder of Cactoos, Takes, Rultor and Jcabi, and a big fan of test automation.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button