As explained above it depends, what you want to test and how is your logic constructed.
Suppose your example
if (CollectionUtils.isNotEmpty(coll)) {
for (String str : coll) {
System.out.println("Branch 1. Collection is not empty.");
}
}
else {
System.out.println("Branch 2. Collection is empty.");
}
In this example, we can see, that always Branch1 or Branch2 is executed.
If we use null expression, the result will be different if coll
is not null but empty
if (coll != null) {
for (String str : coll) {
System.out.println("Branch1. Collection is not empty.");
}
}
else {
System.out.println("Branch2. Collection is empty.");
}
If the collection coll
is not null but it is empty, nor Branch1 either Branch2 is executed, because the condition coll != null
is true, but in loop for
there is not even one pass.
Of course, if
expression coll != null && coll.isNotEmpty()
doing the same work as CollectionUtils.isNotEmpty(coll)
.
Therefore it not advisable programming manner to use test on null in case of collections coll != null
only. This is a case of poorly treated extreme conditions, which may be a source of unwanted result.