Friday, October 14, 2011

Object oriented versus functional interface

I use DateTime::Format::W3CDTF for parsing my dates:

my $w3c = DateTime::Format::W3CDTF->new;
my $dt = $w3c->parse_datetime( $date_string );

I wish it was:

my $dt = DateTime::Format::W3CDTF->parse_datetime( $date_string );

and that the library created the parser on the fly as needed. It's not only less typing - but also much simpler mental model. This simpler model is sometimes too simple - for example if you parse a lot of dates then sparing the parser creation each time can make a difference.

I think the optimal thing to do is provide two APIs - like JSON - a functional one:

$perl_hash_or_arrayref = decode_json $utf8_encoded_json_text;

and an object oriented one:

$json = JSON->new->allow_nonref;
$perl_scalar = $json->decode( $json_text );

for those that need that extra control.

3 comments:

abraxxa said...

my $dt = DateTime::Format::W3CDTF->new->parse_datetime( $date_string );

This creates a parser object, parses the $date_string, returns the DateTime object and destroys the parser object.
But a functional interface will be faster.
The parser object makes sense if you use the same one multiple times.

zby said...

Thanks - your version is indeed better :)

Unknown said...

I'd write my own little function because "DateTime::Format::W3CDTF->new->parse_datetime" is 45 characters.

sub parse_w3cdtf {
   my ($date_string) = @_;

   state $w3c = DateTime::Format::W3CDTF->new;

   return $w3c->parse_datetime($date_string);
}