I have a simple piece of code:
txtRequiredDate.setText(wwDateFormatter.format(todoEntity.getRequiredDate()));
txtRequiredDateDay.setText(dayOfWeek(todoEntity.getRequiredDate()));
txtDoneDate.setText(wwDateFormatter.format(todoEntity.getDoneDate()));
txtDoneDateDay.setText(dayOfWeek(todoEntity.getDoneDate()));
Problem is that sometimes the date is null (as it is optional to fill out). In those cases, the wwDateFormatter triggers a NullPointerException.
One way of fixing it, as I see it is:
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()));
}
But I was wondering if there is a more concise way of writing the above statement?
Thank You!
Edit I guess it’s not that this isn’t optimized, but rather the fact that I’d like to learn various ways of checking for nulls, especially if situation ever arises that I must have 30 of those statements, heh.
Why not wrap the formatter with a null-aware variant that returns an empty string if passed a null ?
You may also be interested in the Null Object Pattern. Also note this blog, which discusses Scala’s
Optionpattern and the equivalent in Java. These are both very useful patterns that you can make use of to mitigate your issue above.