有时开发人员会检查字符串是否为空值,如果是,则将这些字符串设置为空值:
if (text == null) {
text = "";
}
Run Code Online (Sandbox Code Playgroud)
我想做的是写相反的if语句:
if (text.isEmpty()) {
text = null;
}
Run Code Online (Sandbox Code Playgroud)
但是...首先 - 我必须(像往常一样)检查这个 String 是否为 null 以避免 NullPointerException,所以现在它看起来像这样(非常难看,但是 KISS):
if (!text == null) {
if (text.isEmpty()) {
text = null;
}
}
Run Code Online (Sandbox Code Playgroud)
我的类有几个字符串字段,我必须为所有这些字段准备这个解决方案。对于更高效的代码有什么基本想法吗?将其延伸为 lambda 表达式并迭代此类中的所有 String 字段是否是一个好方法?