编写空检查的最简单方法(可能没有IF?)

时间:2012-06-26 13:39:08

标签: java optimization conditional-statements

我有一段简单的代码:

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个这样的陈述,嘿。

3 个答案:

答案 0 :(得分:3)

为什么不使用null-aware变量包装格式化程序,如果传递null,则返回空字符串?

您可能也对Null Object Pattern感兴趣。另请注意this blog,它讨论了Scala的Option模式和Java中的等价模式。这些都是非常有用的模式,您可以使用这些模式来缓解上述问题。

答案 1 :(得分:2)

确保您的日期字符串永远不为空(使用空字符串:""代替) - 如果需要则不再使用。

或者您可以使用非null实用程序方法(类似于Brian建议的那样):

private String nonNull(String s) {
    return (s == null ? "" : s);
}

public void yourMethod() {
    txtRequiredDate.setText(wwDateFormatter.format(nonNull(todoEntity.getRequiredDate())));
    txtRequiredDateDay.setText(dayOfWeek(nonNull(todoEntity.getRequiredDate())));
    ...
}

答案 2 :(得分:2)

这是为什么尽可能避免访问者/属性的典型原因。尝试摆脱暴露实体的“原始”数据并将逻辑放入实体本身 - 然后在一个地方进行空检查。

txtRequiredDate.setText(todoEntity.formattedRequiredDate())

...你在实体方法中进行空检查(并返回空字符串或其他如果为null)。

getter和setter是否真的是邪恶的,old classic article in this subject,是有争议的,但至少在设计实体时考虑封装是一件好事IMO。

相关问题