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?
Optional? Why not try to eliminate null as a factor, opposed to making it a weighted value?StringUtil.notNullAndEmpty(text)methodtext.equals(null)from? This expression is always false or throws an NPE.if (text?.isEmpty() != null), and you can even add methods to String class, likeString#toDisplay().null if empty