Home » Software Development » One More Recipe Against NULL

About Yegor Bugayenko

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.

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.

(0 rating, 0 votes)
You need to be a registered member to rate this.
Start the discussion Views Tweet it!
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

Leave a Reply


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

Notify of