On 2011.9.20 6:09 AM, Bill Moseley wrote:
> Our apps (and the modules they use) use DateTime extensively.   We have the
> need to do a lot of common operations on DateTime objects, for example
> checking if a DateTime object is in the future.  So, I'm wondering what's
> the recommended approach to provide these common methods.
> 
> I think what I'd do is add a method $dt->is_in_future, but I'm not clear how
> we can subclass DateTime since "DateTime->new" is used directly in code we
> don't control.

This is not a problem unique to DateTime, nor even Perl, but a general OO
issue about amending local methods to objects.

You've basically covered the possible solutions.

1) Add the method/role directly to the class.
2) Write a function which takes the object.
3) Add the method/role to the object.

#1 is fine so long as you have a reasonable expectation that your methods
won't collide with somebody else.  If you're doing this in local code (ie. not
a distributed library) that's fine.  I'd add a test to make sure DateTime
itself does not add methods in the future.  The upside of this is you load
your additional methods once and every object has it with no performance loss.
 This technique is often derided because it's widely abused in Ruby.

#2 is the most conservative.  There is no risk to it.  It's confined to your
local namespace.  The downside is it can get annoying when you have a lot of 
them.

#3 basically involves reblessing the object to a subclass of DateTime (that's
what Moose does).  The pros are you won't collide with anyone else, but the
cons are you have to apply it to every object every time.  If nothing else,
it's more typing.  Reblessing carries a bit of risk as things might directly
check the class of your object rather than using isa().  Also you may be
returned an object which acts like DateTime but is not DateTime.  For example,
DateTime::Incomplete or DateTime::LazyInit.  Reblessing these would be 
disastrous.

Personally, if it was local code, I'd do #1 if there's going to be a lot of
methods.


-- 
Stabbing you in the face for your own good.

Reply via email to