Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apache's StringUtils.isBlank(str) vs. Guava's Strings.isNullOrEmpty(str): Should you routinely check for whitespace?

Tags:

Is there any advantage in using

StringUtils.isBlank(str)  

from Apache commons-lang.

vs

Strings.isNullOrEmpty(String string) 

from Google Guava?

I want to replace hundreds of cases of they following usage in a Java project:

if(str == null || str.isEmpty()) 

Guava's isNullOrEmpty seems to be a direct replacement for the usage above in my project.

But more people seem to use Apache's isBlank method based on my reading of S.O. questions.

The only difference seems to be that StringUtils.isBlank(str) also checks for whitespace in addition to checking whether the string is null or empty.

Normally is it a good idea to check a String for whitespace or could that produce a different result in your code than Guava's simpler check?

like image 766
Bryce Marden Avatar asked Sep 07 '11 16:09

Bryce Marden


2 Answers

If you want to use Guava to replicate the isBlank behaviour, I would use the following method instead:

Strings.nullToEmpty(str).trim().isEmpty()

like image 139
dcendents Avatar answered Sep 19 '22 01:09

dcendents


When you have to accept input from human beings, you should be forgiving and strip leading and trailing whitespace from whatever text they type, if it makes sense in the particular application.

That said, using isBlank is only halfbaked. You also need to trim the strings before processing them further. So I suggest to use s = trim(s); before checking with isNullOrEmpty.

like image 24
Roland Illig Avatar answered Sep 20 '22 01:09

Roland Illig