简体   繁体   中英

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

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 SO 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?

如果你想使用Guava来复制isBlank行为,我会改用以下方法:

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

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 .

StringUtils.isBlank(str) is very much different than Strings.isNullOrEmpty(String string)

the first code sample will only check if the string is empty or not, it will include white spaces as well and return true

StringUtils.isBlank(null)      = true 
StringUtils.isBlank("")         = true 
StringUtils.isBlank(" ")        = true 
StringUtils.isBlank("bob")      = false
StringUtils.isBlank("  bob  ")  = false

where as Strings.isNullOrEmpty(String string) Returns true if the given string is null or is the empty string

isBlank is incredibly overrated. UI code that reads user text straight out of input fields can trim whitespace once and for all, and then you can stop worrying about it.

Guava is more or less targeted towards being a 'next generation' replacement of Apache Commons. There really isn't much practical difference between using isBlank() vs isNullOrEmpty() beyond using one or the other consistently.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM