Tuesday, November 15, 2005

Lesson of Java date and time classes

It happened so that I didn’t use Java date- and time-related classes for a long time. I didn’t like them, and I was lucky enough that I didn’t need them, too. Well, sooner or later that should have happened – today I needed to use some date arithmetic. I opened the Javadoc, and spent next half-an-hour trying to understand, how these classes should be used.

I succeeded, and the result was not as ugly as I expected. The question is, why these classes are so counterintuitive and overcomplicated? I had to use 3 different classes to do a relatively simple thing: Date class to store date in milliseconds; Calendar class to perform arithmetic; and SimpleDateFormatter class to print the date and to parse string input.

There are many classes, they are complex – but still some of the most mundane tasks are not that easy to do. How difficult is for us to answer a question: “What date is the next Saturday?” Easy, right (if we have calendar at hand, of course)? Then try doing it using Java classes. Yes, it is possible – and not that difficult – but, still, it is much more complex process than it should be.

The lesson here is simple: create façade for complex classes so that simple common tasks can be easily done – and for more challenging things (what if I need to print a Hebrew calendar in Klingon?)  there are always more powerful tools.


Anonymous said...

I have to admit, that although you logic seems flawless, there are certain implications that you are missing. As you said yourself: How easy it is to find what date next saturday is? So easy when you have.... "Calendar". It is logical that person uses calendar to find what the next date is. As you can see you contradicted yourself. JDK util classes such as Date, Calendar etc where never ment to use as a front end util classes in application. It is always reasonable to create your own APPLICATION specific set of utils which will be comfortable FOR YOU to use. Just watch out for SimpleDateFormat class - it is not thread safe :)

Aleksey Linetskiy said...

Thanks for note about SimpleDateFormat being not threadsafe!

And as for

It is always reasonable to create your own APPLICATION specific set of utils which will be comfortable FOR YOU to use.

- well, in theory I will agree. But the same logic can be easily applied to any assembler :) I think that one of the reasons for existence of high level languages and standard libraries is to allow the programmer do simple common things in a simple way, without having to reinvent the wheel.