So, I was playing around a little in Ruby and noticed that
DateTime
is a subclass of
Date
, yet the method
today
is
not defined for it. I asked
Venkat about it (in an email), he inspected the source code (why didn't I think of that?), and he replied that
the culprit! is line 1261 in date.rb, within DateTime class
class << self; undef_method :today end rescue nil
I thought it was interesting: Certainly this violates
LSP, yet certainly a DateTime shouldn't have the method
today
. So, are there instances where it makes sense to violate LSP, in favor of keeping up with the metaphor?
I wonder why
Date
isn't a subclass of
DateTime
, rather than the other way around? At least for this case, it would not have violated LSP. So, I posted about this on the
Ruby-Talk mailing list - I'll update you when I hear back from that group.
Update: I just realized if we made
Date
a child of
DateTime
, we'd get a similar problem in that we'd be removing the time part from the class. How would you resolve it?
Update 2: After some thought and some help from the Ruby community, I'm not so sure this is a violation of LSP. You see, the method
today
can only be called on
Date
, not an object of
Date
. So therefore, there is no violation when an object of
Date
is replaced by one of
DateTime
. Robert Klemme chimed in with this, which of course I addressed above, but he said it much better than I did:
Once can certainly argue whether DateTime *is a* Date or rather *has a* Date. But it is definitively clear that Date *is not* a DateTime simply because it does not provide the same set of information that DateTime provides (date *and* time)
So in the end, it appears as if there is no problem at all. Sorry for being alarmist - I guess I should have tested it first, right? =).
Hey! Why don't you make your life easier and subscribe to the full post
or short blurb RSS feed? I'm so confident you'll love my smelly pasta plate
wisdom that I'm offering a no-strings-attached, lifetime money back guarantee!
Leave a comment
There are no comments for this entry yet.
Leave a comment