How do I implement the Null Object pattern with Date?

I would like to use Null Object Pattern for java.util.Date. I have a function that returns some date, but it may also be that no meaningful date can be returned.

I would like to avoid returning null

for the usual reasons you would like to avoid nulls (nullpointer problems).

At the moment I am returning new Date(0)

for indicating a "date zero" and checking for returnedDate.equals(new Date(0))

downstream where I need to know if I have a real date or not, but I'm not sure if this is the best way.

+3


source to share


2 answers


Optional

Class

Try using a class Optional

added in Java 8. This article demonstrates.



Guava Library

The Google Guava library is of a similar type. This article explains.

+3


source


I'm a little confused about what you are asking.

If you declare an object of new Date()

any type, then the object will never be null. I think what you are trying to do is to set the date to null and instead create an arbitrary date new Date(0)

for use later in your program.

I would advise against this practice and I don't think this is the best way.

My recommendation is to keep the object null and do some kind of validation:

Date date;
if(date != null)
{
    // code goes here
}

      



In essence, you, I think, have already done this check (by checking an arbitrary date object).

As a reminder, here are the following date parameters defined in the Java class Date

:

// Creates today 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

downstream object in your program, when I suggest creating it.

Feel free to provide more information / more code to help guide this discussion.

0


source







All Articles