Reputation: 3955
I would like to use the Null Object Pattern for java.util.Date. I have a function that returns some Date, but it can also be that no meaningful Date can be returned.
I would like to avoid returning null
for the usual reasons why one would like to avoid nulls (nullpointer issues).
At the moment I am returning new Date(0)
to indicate an "null date" and checking for returnedDate.equals(new Date(0))
downstream where I need to know whether I have a real date or not, but I'm not convinced that this is the best way.
Upvotes: 3
Views: 607
Reputation: 3496
Optional
ClassTry using the Optional
class added to Java 8. This article demonstrates.
The Google Guava library has a similar type. This article explains.
Upvotes: 3
Reputation: 6258
I'm slightly confused at what you're asking.
If you are declaring a new Date()
object of any kind, then the object will never be null. I think what you are trying to do is avoid setting a Date to be null and instead creating an arbitrary date, new Date(0)
to use later in your program.
I would advise against this practice and I don't think it's the best way.
My recommendation is to keep the object null and make some sort of check:
Date date;
if(date != null)
{
// code goes here
}
In essence, you – I think – are already doing this check (checking for the arbitrary date object).
As a reminder, here are the following date parameters as defined in the Java Date
class:
// Creates today's date/time
Date()
// Creates a date
Date(long)
Date(int, int, int)
Date(int, int, int, int, int)
Date(int, int, int, int, int, int)
Date(String)
Once you have enough information to create the Date
object downstream in your program is when I would advise creating it.
Feel free to provide more information / more code to aid in this discussion.
Upvotes: 0