In if-statements in Java code i often read something like if(string != null && string.isEmpty() == false). I was used to write if(string != null && !string.isEmpty())
Are there any disadvantages of using !string.isEmpty()?
In terms of behaviour
if(string != null && string.isEmpty() == false)
and
if(string != null && !string.isEmpty())
are obviously identical. I prefer the latter, only because it's slightly more concise. Where possible, I prefer to express conditions positively, but unfortunately there is no string.isNotEmpty() method
So in general when I want to check if a String is either null or empty (in a null-safe fashion) I use:
StringUtils.isNotBlank(string)
This StringUtils class is from the Apache commons lang library, but you can easily write your own if you don't already have this on your classpath and don't want to add it.
There aren't any disadvantages I can think of. It's just a matter of personal coding style and preference. Personally I would also prefer if(!string.isEmpty()).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With