Sometimes developers checks if Strings are null values, if yes, sets those Strings as empty value:
if (text == null) {
text = "";
}
What I want to do is to write opposite if statement:
if (text.isEmpty()) {
text = null;
}
But...first of all - I have to check (as usually) if this String is null to avoid NullPointerException, so right now it looks like this (very ugly but KISS):
if (!text == null) {
if (text.isEmpty()) {
text = null;
}
}
My class has several String fields and for all of them I have to prepare this solution. Any basic ideas for more efficient code? Is it a good way to strech it to lambda expressions and iterate throught all String fields in this class?
Another alternative using Guava's emptyToNull:
text = Strings.emptyToNull(text);
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