So I've noticed that one of Dart's unique abilities that it has over other languages is that you can override "primitive" comparisons (<, >, <=, >=, ==
) in order to implement your own methods.
Now I was also looking through the DateTime class documentation to understand what it is and how to use it, and I noticed that they've opted to have the named methods DateTime.isBefore(DateTime other)
and DateTime.isAfter(DateTime other)
. In human/pseudo code, these would translate to dateTime < other
and dateTime > other
, and naturally I thought why not just implement this directly into Dart?
I know this can be done using extensions as in this DartPad, and sure enough it works exactly as expected and to my knowledge, there's no way to know that an extension is being used...
But why wasn't overriding operators considered when developing the DateTime
object? Or if it was considered, why wasn't it included?
For several reasons, but mainly because the ordering is not compatible with ==
.
Two DateTime
objects are equal if they have the same time and timezone, but they are considered before/after each other based entirely on the time, as modified for timezone.
It was considered a bad design to have a <= b
which was not the same as (a < b || a == b
), and for that reason, <
and <=
was dropped entirely.