I have read this topic: Avoiding != null statements but I don’t see benefits.
-
If you return empty array, you need to examine where the “real” array is, and where the empty array is.
-
Instead of using code like
getName() != null, you must usegetName().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?
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
nullvalue, at its core, is simply far more prone to errors due to its nature.Take the following code, for example:
The check for
nullis 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:
Once again, you need a
nullcheck. If the action is guaranteed to exist, then you can always callaction.run()with no side effects, yet the blank actions just won’t do anything. It’s that simple.In many cases,
nullchecks can simply be discarded if you modify how methods return, leading to much simpler and understandable code. In some cases, returningnullis the correct choice (for example, getting an object from a collection of keys and values), since there is no default “actionless” value. Butnullindicates 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
nullis 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, useasserts or exceptions. Those are failures. Don’t usenullas a failure case, use it as a simple lack of a value.