Best Way to Handle Blank Dates in Java

java

I'm trying to create a contact book application, and currently I'm working on a class called Person. One of the fields of person is dateOfBirth, however I don't know how to handle unknown dates. Until now I have been using java.time.LocalDate for dateOfBirth and I've been initialising the field to null at instantiation. This isn't ideal, because it's resulting in null pointer exceptions when I try to compare dateOfBirth to other dates such as the LocalDate.now().

What would be the best way to handle dateOfBirth? Should I just create an entirely new class and manage unknown dates internally? Or is ther some better way to do it. I was going to just extend LocalDate but it's immutable so can't be extended without going to the source.

Best Answer

Use the class Optional<LocalDate>

This useful container class was introduced in Java 8. It is a wrapper used for values which you might or might not know. It is unboxed with various methods which all allow you to handle the case that the value is unknown in a graceful manner.

  • get() unboxes the LocalDate, but throws a NoSuchElementException in case you have none. Unfortunately it is an unchecked exception, just like the dreaded NullPointerException. So I would recommend to avoid using this method and instead use:
  • orElseThrow(exception) which throws said exception when you don't have a value. The exception can (and should be) a checked exception so you are forced to handle it. Don't feel like writing a clunky try...catch... construct? In that case:
  • ifPresent(Consumer<? super T> consumer) is a useful construct when you want to execute some code only if you have a value and otherwise do nothing.
  • orElse(T value) unboxes the value but gets you the dummy value you provide when you have none

For more information, check the article "Tired of Null Pointer Exceptions? Consider Using Java SE 8's Optional!" on Oracle Tech Net and the documentation to see what other methods it provides.

Not using Java 8 yet?

When you are still using an older version of Java, you could easily improvise your own OptionalDate class, which has just:

  • private LocalDate
  • public void set(LocalDate value) and
  • public LocalDate get() throws DateUnknownException

By having the getter throw a checked exception you are forced to always handle the null-case.

Related Topic