Doug Treder wrote:
> The "fuzzy logic" that was being described earlier on the list is more
> attractive. There are definitely edge cases where two durations
cannot
> be compared and should throw exception. But most of the spectrum is
> actually comparable, depending on the units being compared: 30 seconds
> is always less than 31 seconds, 1 day is always less than 1 month. In
> fact just taking the worst case for every unit still leaves most of
the
> spectrum comparable. You can determine a span of "worst fuzziness"
for
> each unit (months are fuzzy for at least 3 days, possibly 4) and throw
> exceptions if the duration comes within that range.
I really, really, really don't like this. If I get two durations I want
to be able to compare them or not compare them. I don't want to have to
handle the 'fuzzy' bits. Here's how you'd have to handle 'might
compare':
my $cmp = eval{ ($dtdurr1 < $dtdurr2) };
if ($@) {
$cmp = DateTime->now()->add_durration( $dt_durr1 )
<
DateTime->now()->add_durration( $dt_durr2 );
$cmp_from_now++;
}
if ($cmp) {
print "dtdurr2 is the larger";
print ($cmp_from_now)
? " using now() as a base"
: " for any base";
}
__END__
However, to compare with compare() is much easier:
if ($dtdurr1->compare($dtdurr2) == -1) {
print "dtdurr2 is the larger using now() as a base"
}
And, to make comparing easier, we could add is_less_than and
is_greater_than and is_equal_to:
sub is_greater_than { (return shift->compare( @_ ) == 1) }
sub is_less_than { (return shift->compare( @_ ) == -1) }
sub is_equal_to { (return shift->compare( @_ ) == 0) }
Of course, you could always write DateTime::Utils::DurationFuzzyCompare
which could either take a Duration for its new() parameter, or could be
Class::ClassDecorator on top of DateTime::Duration.
Cheers!
Rick