Monthly Archives: February 2009

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??


Effective Java

Ok, I know. Shame on me. I should have read this book a loooooong time ago. This book is a little bit dated now; it’s from 2002, and the 2nd edition is already out.

Anyway, I finally came to it and it is worth every word. To be honest, I haven’t finished reading it yet, but it is nonetheless the best Java book I’ve ever read.

Effective Java

Effective Java

One of the things I loved the most in this book is that the author discusses everything in detail, explaining the “whys”. This is amazing, because you can merge this information with your own opinion and experience and end up having a new, better understanding of Java.

For example you, as the good programmer you are, certainly know that you should REALLY prefer composition over inheritance. But do you know why? Better yet, do you now how much inheritance can be GREATLY insecure? Well, this book explain this and shows very good examples.

I’m really looking forward to reading the 2nd edition now!


Follow

Get every new post delivered to your Inbox.