Maybe I'm an old fart, but I think that writing your own accessor factory is a rite of passage for every aspiring Perl hacker ...
Sure it is, but Moose is so much more then an accessor factory and when it comes to getting real work done why add an object system to your maintenance burden?
You can take eric256's example one step further and make 'tablename' required (meaning you *must* supply a value to the constructor), and set default values for all the other attributes. I also made the grouped attributes "lazy" which means that Moose will not initialize the slot until it absolutely has too.
package DataTable;
use Moose;
has 'tablename' => (is => 'rw', isa => 'Str', required => 1);
has 'columns' => (is => 'rw', isa => 'ArrayRef[Str]', default => sub
+ { [] });
has 'indices' => (is => 'rw', isa => 'HashRef[Str]', default => sub
+ { +{} });
has 'datatypes' => (is => 'rw', isa => 'ArrayRef[Str]', default => sub
+ { [] });
has [qw/ lengths decimals signed allownull default usequote /] =>
(is => 'rw', isa => 'ArrayRef[Int]', lazy => 1, default => sub { [
+] });
1;
This is not much more code for Moose, but adding it to your example, or the OPs example would start to get really hairy.
And then to take it even one more step further using Moose::Meta::Attribute::Native you can add some delegated behavior to the 'columns' attribute like so:
package DataTable;
use Moose;
has 'tablename' => (is => 'rw', isa => 'Str', required => 1);
has 'columns' => (
traits => [ 'Array'],
is => 'rw',
isa => 'ArrayRef[Str]',
default => sub { [] },
handles => {
'add_column' => 'push',
'remove_column_at_idx' => 'delete',
# ... and many more
}
);
# rest of the class snipped off for brevity ...
This can then be used like this ...
my $dt = DataTable->new;
$db->add_column( 'foo' );
$db->add_column( 'bar' );
# columns is now [ foo, bar ]
$db->remove_column_at_idx( 0 );
# columns is now [ bar ]
Honestly, would you want to write this into your own accessor generator? Would you want to maintain it? Moose has *thousands* of tests to make sure stuff like this Just Works.
|