我有一段简单的代码:
txtRequiredDate.setText(wwDateFormatter.format(todoEntity.getRequiredDate()));
txtRequiredDateDay.setText(dayOfWeek(todoEntity.getRequiredDate()));
txtDoneDate.setText(wwDateFormatter.format(todoEntity.getDoneDate()));
txtDoneDateDay.setText(dayOfWeek(todoEntity.getDoneDate()));
问题是有时日期为空(因为它是可选填写的)。在这些情况下,wwDateFormatter 会触发 NullPointerException。
据我所知,修复它的一种方法是:
if (todoEntity.getRequiredDate() != null)
{
txtRequiredDate.setText(wwDateFormatter.format(todoEntity.getRequiredDate()));
txtRequiredDateDay.setText(dayOfWeek(todoEntity.getRequiredDate()));
}
if (todoEntity.getDoneDate() != null)
{
txtDoneDate.setText(wwDateFormatter.format(todoEntity.getDoneDate()));
txtDoneDateDay.setText(dayOfWeek(todoEntity.getDoneDate()));
}
但是我想知道是否有更简洁的方式来编写上述语句?
谢谢!
编辑我想这并不是说这没有优化,而是事实上我想学习检查空值的各种方法,特别是如果出现我必须有 30 个空值的情况这些陈述,呵呵。
最佳答案
为什么不使用 null 感知变体包装格式化程序,如果传递 null 则返回空字符串?
您可能还对 Null Object Pattern 感兴趣。另请注意 this blog ,其中讨论了 Scala 的 Option
模式以及 Java 中的等效模式。这些都是非常有用的模式,您可以利用它们来缓解上述问题。
关于java - 编写空检查的更简洁的方法(可能没有 IF?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11208580/