Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java There's any use on a simple "isNull"/"isNotNull" function?

I'm feeling quite silly for asking this question, but I've already seen this code on two separate corporate codebases and I'm starting to think there's some chunk of ancient java knowledge I'm not aware of.

So, we got this kind of code:

/* Lot of corporate stuff */
if (ClassicUtilsClass.isNotNull(variable)) {
    /* Variable handling shenanigans. */
}

Going to our ClassicUtilsClass revealed the implementation of the function:

/* Lot of useful static functions*/
public static isNotNull(Object o) {
    return o!=null;
}
public static isNull(Object o) {
    return o==null;
}

I read it, scratched my head, looked around the internet, asked colleagues and friends, then laugh at the uselessness of the function. Then I switched jobs and a colleague showed me more or less the same code.

In the same codebase we have the classic "isNullOrEmpty" which does the standard "return object==null || object.size() == 0;", so I can understand having a function to wrap the null comparison... plus something else, but I don't see the point of creating a whole new function for null checking.

I'm losing something here?

like image 264
Neuromante Avatar asked Jan 06 '23 00:01

Neuromante


2 Answers

There are similar functions in the Objects utility class, called nonNull and isNull. The reason they are provided is to be used as predicates, e.g.

...stream().filter(Objects::nonNull)...

I can't see any reason to use

if (SomeClass.isNotNull(x))

rather than the shorter, clearer

if (x!=null)
like image 75
khelwood Avatar answered Jan 13 '23 18:01

khelwood


There are only a few reasons to implement operators as methods that I can think of.

The first reason is to "profile" how many times the operation is used in an application. Profiling tools count the time spent in methods and the number of times methods are called but they don't track operator usage.

The second reason to implement operators as functions is to use them in functional programming constructs. Operators cannot be passed around using reflection, but methods can, so it is possible to create functional operations (map, reduce, etc) that use reflection and in those cases operators would need to be implemented as methods to be utilized.

A third possible reason to implement the not null operator as a method is to simplify the automated translation of some other programming languages into java. In java primitive types cannot be null so checking if they are null directly using the == operator would cause a compiler error. Java will autobox primitives into objects so they can be used as arguments to methods which accept Object as their argument type. In this case a code translator could translate null checks to method calls without needing to track the variable type.

like image 34
Ralph Ritoch Avatar answered Jan 13 '23 18:01

Ralph Ritoch