Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a benefit of avoiding != null in java?

Tags:

java

null

I have read this topic: Avoiding != null statements but I don't see benefits.

  1. If you return empty array, you need to examine where the "real" array is, and where the empty array is.

  2. Instead of using code like getName() != null, you must use getName().length > 0. As an example, I'm working on project, where I need to compress some data with few archivers and decided to choose compressed data with the smallest size. If I return null from the archiver "compress" method, I need to check that the returned value is not null. If I decided to return an empty array, then I also need to check it for empty.

Am I right?

like image 804
Avershin Dmitry Avatar asked Dec 01 '22 23:12

Avershin Dmitry


1 Answers

The primary advantage of using empty collections or "blank" actions instead of null is that most of the time, such objects will still work in code without further modification. The null value, at its core, is simply far more prone to errors due to its nature.

Take the following code, for example:

String[] names = data.getNames();
if (names != null) {
    for (String name : names) {
        // Do stuff
    }
}

The check for null is required or you'll get an NPE. Using a standard for loop does not resolve the problem. On the other hand, if you know you'll always get an array of some kind, your code will work fine with no additional checks. The loop won't run at all if the array is empty. Problem solved.

The same is true for code that implements some form of action. Another example:

Action myAction = data.getActionToRun();
if (myAction != null) {
    myAction.run();
}

Once again, you need a null check. If the action is guaranteed to exist, then you can always call action.run() with no side effects, yet the blank actions just won't do anything. It's that simple.

In many cases, null checks can simply be discarded if you modify how methods return, leading to much simpler and understandable code. In some cases, returning null is the correct choice (for example, getting an object from a collection of keys and values), since there is no default "actionless" value. But null indicates the lack of a value at all, and it requires additional handling be the receiver. Using blank, actionless, non-null objects allows the error to be handled by the data object. That's good encapsulation. It's good programming. It just works.™

Finally, returning null is certainly not a good way to handle errors. If something goes wrong in your code that should never go wrong unless you as the programmer made a programming mistake, use asserts or exceptions. Those are failures. Don't use null as a failure case, use it as a simple lack of a value.

like image 185
Alexis King Avatar answered Dec 03 '22 12:12

Alexis King