Store date attributes as primitive longs?

I was reading the item 24 of this book and, in one of the last paragraphs, the author comments about storing date objects as a primitive long. The text is about making defensive copies of objects in your constructors and accessor methods.

So instead of


public void setDate(Date date) {

    this.date = date;

}

you should use


public void setDate(Date date) {

    this.date = new Date(date.getTime());

}

This is pretty obvious after years developing O.O. software, and explaining it is out of the scope of this post. Now, about using primitive longs. It actually seems to be a very interesting idea. Since you would have to use the long value of the local (private) date all the time to create the defensive copies, storing it as a primitive long right away would get us more clean and readable code.

The constructor would simply store the long date, and the acessor would be as simple as


public Date getDate() {

    return new Date(myDateAsLong);

}

Also, it would be easier to store the date in the database, since we wouldn’t need to convert a Date object to a format the database understand.

Now, the bigger question: why didn’t I think about this before??


2 Responses to “Store date attributes as primitive longs?”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.