Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any disadvantages of writing !string.isEmpty()?

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()?

like image 480
Martin Schlagnitweit Avatar asked Nov 24 '25 09:11

Martin Schlagnitweit


2 Answers

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.

like image 195
Dónal Avatar answered Nov 26 '25 22:11

Dónal


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()).

like image 40
Darin Dimitrov Avatar answered Nov 27 '25 00:11

Darin Dimitrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!