Dear readers,

I think java.time.Duration is a pretty useful class and after having to
work a lot with it, I recognized there might be some enhancements we
could make (where 'enhancement' is a subjective term of course).

For instance:

Comparison
----------
  boolean isGreaterThan(Duration duration) / isLongerThan(..)
  boolean isSmallerThan(Duration duration) / isShorterThan(..)

English is not my primary language so I don't know which of these
aliases would be better. Given that classes such as Instant and
OffsetDateTime also have comparison methods (isAfter, isBefore), I
think it would be useful if Duration had easy comparison methods. Of
course we have compareTo(..) but I always get confused what it actually
means when I get a positive or negative number. :)

More comparison
---------------
  static Duration max(Duration d1, Duration d2)
  static Duration min(Duration d1, Duration d2)

Returns the longest resp. shortest of the two durations, where negative
durations are shorter than positive durations.

Side note: I have not found an easy method to obtain the max resp. min
values of elements which implement Comparable, I could only come up
with something like:

  Stream.of(Duration.ZERO, Duration.ofSeconds(1L))
    .max/min(Comparator.naturalOrder())
    .orElse(null);

It could be worthwile to add generic methods such as
  public static <T extends Comparable<T>> T max(T... elements)
  public static <T extends Comparable<T>> T min(T... elements)
in the Comparator class.

Disallowing negative value
--------------------------
Okay, this one is a bit more farfetched, but a method which would be
useful for my use case is to have an alternative of between() which is
never negative and just truncates to zero if it happens to be negative.

I'm measuring a duration between timestamps which come from different
systems which should be in sync with their NTP servers (and each
other), but there may still be some time dilation which could lead to
weird results making it look like the effect happened before the cause.

So I could see some use for a method like:

  Duration positiveOrZero()


Kind regards,

Dave Franken

Reply via email to