Skip navigation

There was a time when dealing with dates and times in Java was god-awful. With Joda Time, everything’s a breeze. Not only are date-based calculations easy, but you can also make your domain code less anemic by utilizing the library to its full extent.

Case in point: I had a method that returned objects due for removal in the next n months. Its signature first looked like this:

List<Thing> findThingsDueForRemovalIn(int months);

Using Joda, I first found a way to make the parameter type communicate the intent better. Enter Months:

List<Thing> findThingsDueForRemovalIn(Months months);

Now you can’t just call the method without thinking first; we actually had a bug in production recently due to one setXXXTimeout(...) method accepting seconds and the other milliseconds, both as primitive numbers. In the same class. Oh, the confusion.

The implementation is clean as well, something along the lines of

public List<Thing> findThingsDueForRemovalIn(Months months) {
  ...
  final LocalDate today = new LocalDate();
  someQuery.setInclusiveDateRange(today, today.plus(months));
  return someQuery.execute();
}

Small victories.

One Comment

  1. Wonderful! Plus now you could do:

    List findThingsDueForRemovalIn(ReadablePeriod time);

    …and then find removable things with anything – be it months, days, years or even esoteric combos (22 minutes & 17 seconds == 1337 seconds)!

    “A good API a day keeps anemia away!”


Leave a comment