Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

One More Recipe Against NULL [Snippets]

DZone's Guide to

One More Recipe Against NULL [Snippets]

Many developers think NULL is evil. Is it? We take a look at what to do when it comes to returning it, as well as a lesson taken from Python.

· Java Zone ·
Free Resource

Get the Edge with a Professional Java IDE. 30-day free trial.

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.

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.

Get the Java IDE that understands code & makes developing enjoyable. Level up your code with IntelliJ IDEA. Download the free trial.

Topics:
null ,best practice ,java ,exceptions

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}