Thursday, March 5, 2009

The joy of refactoring

Imagine you have an infrastructure that allows you to run batch jobs asynchronously. However, you can't specify exactly when you want it to run (à la cron) but rather all you have is a polling interface, so your "service" will start up every x mins, do something, then sleep again. Finer grained control is up to you.

This is our situation, and we usually specify a start time, eg - "23:00", an end time "24:00", and have a bit of logic somewhere to abort the run if the current time is outside that window. I finally noticed the bit of logic that does this, and realised that it was duplicated in every service has a *copy* of the same code. behold:


Needless to say, I didn't like the duplication, or the code itself. I didn't have scope to retrofit the other services that used similar code, but I could fix this one and build a foundation for later.

First step was to refactor that mess out to a common util class, leaving us with this:

and this:

The first cut was just a raw refactor extract, the next step was to not use ugly Calendar code and handle the midnight cutover correctly (which is actually quite hard!). After a few false starts with Dates and dealing with GMT and daylight savings offsets, we ended up with this (convenience methods and javadoc not shown), which is unit-tested and guaranteed to work (except maybe during the daylight savings cutover itself..)

Much nicer, well we think so anyway.

If you can see a bug in there please let me know!!

No comments: