develooper Front page | perl.datetime | Postings from April 2017

Subclassing DateTime?

Thread Next
April 29, 2017 18:14
Subclassing DateTime?
Message ID:
Dear list,

A pattern seen frequently in DateTime::Calendar-like modules is to put the functionality in a top-level module which holds a DateTime object to do the DateTime-specific stuff. If you want anything like the full DateTime functionality this involves writing a bunch of methods on the order of

sub some_method { $_[0]->{dt}->some_method( @_[ 1 .. $#_ ] ) }

Fortunately if I turn off strict refs the methods can be defined in a loop by assigning an anonymous subroutine to a glob. But the above is not the only subroutine template, merely the most common.

It seems to me that in at least some such cases subclassing DateTime would be a better alternative. But I find no documentation on how to do this. I made a sort of middle-level pass through, and browsed the mailing list archives back to 2012 or so. Did I miss the documentation somehow? If so, could someone give me a pointer to it?

The main issue I see are:

* Where can I, in some supported way, stash any extra attribute values?

* Is there a naming convention to avoid method name conflicts (i.e. unintentional overrides), especially for private methods?

You can stop reading here unless you are curious about what motivated the question. Feel free to snip it in a reply.

My reason for asking is that I have adopted a couple modules that use this pattern: DateTime::Calendar::Christian and DateTime::Fiction::JRRTolkien::Shire. Both were missing some DateTime functionality of interest to me -- a lot in the latter case. A bunch of methods had to be written to get it, and these methods have a strong family resemblance.

When I was going through the process of adopting DateTime::Calendar::Christian I was offered DateTime::Calendar::Liturgical::Christian. I refused, because I do not have the religious background to understand the first thing about what feast we celebrate today or what color altar cloth to use; DateTIme::Calendar::Christian just does the Julian calendar before the conversion date and the Gregorian calendar after.

Well, I decided to take another look at DateTime::Calendar::Liturgical::Christian, found myself writing those same methods for a second or third time, and decided maybe some laziness was in order. I started writing a class that does not inherit from DateTime but uses the $self->{dt} pattern, AND that passes all the DateTime tests. This is mostly just drudgery, but the methods that take two DateTime arguments (e.g. subtract_datetime()) are turning out to be problematic. So I thought, belatedly, that I would look into doing the simple obvious thing rather than the complex obscure thing.


Tom Wyant

Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About