in reply to Re^4: OO automatic accessor generation
in thread OO automatic accessor generation
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.
This is not much more code for Moose, but adding it to your example, or the OPs example would start to get really hairy.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;
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:
This can then be used like this ...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 ...
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.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 ]
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^6: OO automatic accessor generation
by BrowserUk (Patriarch) on Nov 12, 2009 at 08:20 UTC | |
by stvn (Monsignor) on Nov 12, 2009 at 21:10 UTC | |
by BrowserUk (Patriarch) on Nov 12, 2009 at 22:09 UTC | |
by stvn (Monsignor) on Nov 12, 2009 at 22:33 UTC | |
by BrowserUk (Patriarch) on Nov 12, 2009 at 23:16 UTC | |
| |
|
Re^6: OO automatic accessor generation
by WizardOfUz (Friar) on Nov 12, 2009 at 11:21 UTC | |
by stvn (Monsignor) on Nov 12, 2009 at 20:06 UTC |