I’ve been looking through the API for JSR 310 Date & Time revamp presumably slated for Java 7. There are many nice things in it, especially compared to the craptastic java.util.Date and Calendar. Throughout, the API relies on factories, immutable objects, and a host of other recommended API patterns.
But I wanted to mention one of my favorite things, which is the Clock class that acts as a facade for accessing the current time. I use “time” here somewhat loosely; in keeping with the nature of the 310 API, you can get the current point on the timeline (like System.currentTimeMillis()) or the current date, time, date/time, etc.
Anyhow, Clock is an abstract class. You actually need to get an instance of it to use it and typically you’ll use the one provided by the static method Clock.system() with something like this: [source:java]
// Use pre-defined system clock
Clock clock = Clock.system();</p>
// Create instant (nanoseconds since the epoch)
Instant now = clock.instant();
// Create human scale date (no time)
LocalDate today = clock.today();
The cool part is that Clock is intended to be subclassed so that you can control the advancement of the clock yourself, like this guy:
This is awesome for unit testing as you can create your own Clock, fix the time, control the rate at which it advances, test rolling over daylight savings time changes, time zones, etc. But all of your code just relies on Clock, which is the standard facade.
I’ll be doing a new Java 7 Preview talk in my last three No Fluff Just Stuff conferences this season if you’re interested in checking it out: