I’ve been working in Liferay code, and I’ve come across this construct a few times:
List<?> list;
...
if (Validator.isNotNull(list)) {
//do stuff
}}
The source code for Validator.java
looks like this:
public static boolean isNotNull(Object obj) {
return !isNull(obj);
}
public static boolean isNull(String obj) {
...
}
public static boolean isNull(Long obj) {
...
}
public static boolean isNull(Integer obj) {
...
}
public static boolean isNull(Object obj) {
if (obj instanceof String) {
return isNull((String)obj);
}
if (obj instanceof Long) {
return isNull((Long)obj);
}
if (obj instanceof Integer) {
return isNull((Integer)obj);
}
return obj == null;
}
So my question: what are the benefits of calling Validator to do this function rather than simply writing if (obj == null)
? Do these function calls add a significant enough overhead that it is worth avoiding this method of programming?
0
Look at the implementation of isNull
for different types. Such as string
:
public static boolean isNull(String s) {
if (s == null) {
return true;
}
s = s.trim();
if ((s.length() == 0) || (s.equals(StringPool.NULL))) {
return true;
}
return false;
}
This is not the same as obj == null
, because if obj
has a value of “t “, the null comparison will return false
. On the other hand, isNull
will return true
because of the s = s.trim()
followed by s.length() == 0
.
If you’ve used .NET Framework, the isNull(String s)
is what is called string.IsNullOrWhiteSpace()
—a much better name for the method.
For instance, in your first piece of code, if list
is an empty, non-null list:
-
list == null
will returnfalse
, -
Validator.isNull(list)
will returntrue
.
Do these function calls add a significant enough overhead that it is worth avoiding this method of programming?
Since the method doesn’t do the same thing as obj == null
, comparing its performance makes no real sense. The caller of isNull
uses this method because it is convenient when checking for, say, a null or empty list, or a null, empty or whitespace string.
Obviously, if the only thing you need is to check whether the variable is null, just do obj == null
; Validator.isNull
is not for that (despite its name).
Note that the isNull(Object)
overload does an additional job of comparing the type of the object and eventually doing a cast. This means that when using the validator library, you should try to always work with typed variables. For instance:
Object obj = this.loadSomethingFromProxy();
if (Validator.isNotNull(obj))
{
something = (Long)obj;
this.doStuff(something);
}
should be refactored into:
Long something = (Long)this.loadSomethingFromProxy();
if (Validator.isNotNull(obj))
{
this.doStuff(something);
}
because in the later case, you are doing the cast only once (instead of twice) and then call the isNotNull(Long)
overload, skipping type checking.
5