Sunday, August 06, 2006

java.util.Date must die

I find java.util.Date to be most of the most annoying class in the entire Java class library. It is essentially a wart left over from Java 1.0, but the fact that it is used in many APIs makes it difficult to remove.

The most insidious aspect of Date is that despite being nothing more than a wrapper around a long, Date is mutable. Anyone can call the setTime method and change the internal long. That causes problems with methods changing Date instances that are passed to them and code accidentally changing Date instances that are members of collections. What benefit comes from Date being mutable? Java understands the benefits of immutable objects. String is immutable. Long is immutable. Why not Date?

What's worse is that the SQL date types specified by JDBC inherit from java.util.Date, making them mutable too! That's in addition to the general inconvenience imposed by having them in the first place.

The inconvenience of Date might be acceptable if it actually did something, and in fact, in Java 1.0, the Date class did have useful functionality. But since Java 1.1, Date does nothing. Nothing! All of the useful methods of Date were deprecated and replaced by java.util.Calendar. But for some reason, setTime survived the purge.

I'd like to see Date.setTime deprecated and the Calendar-like accessor methods reinstated. Why did those other methods have to be deprecated? They could have been respecified in terms of Calendar and could have operated on an internal thread-local Calendar instance, allowing developers to write


int year = someDate.getYear();


rather than


Calendar calendar = Calender.getInstance();
calendar.setTime(someDate);
int year = calendar.get(Calendar.YEAR);


And while I'm there, didn't anyone think that was odd that the method to pass a Date into Calendar is called setTime? How about setDate! Then the method that passes a long into Calendar could have been called setTime, just like the same method of Date.

0 Comments:

Post a Comment

<< Home