http://www.perlmonks.org?node_id=139911

Recently, one of the projects that I have been working on has many duplicate method calls. I have refactored out much of the duplicate code that remains, but they are still pretty much the same. Here are two examples:

sub add_company { my ( $self, $data ) = @_; my $table = 'company'; my $data = $self->_generic_insert( $data, $table ); $self->{ _dbh }->commit if ! $self->{ _error }; return $data; } sub add_financial_diary { my ( $self, $data ) = @_; my $table = 'financialDiary'; my $data = $self->_generic_insert( $data, $table ); $self->{ _dbh }->commit if ! $self->{ _error }; return $data; }

Note: I don't feel the need for transactions here, but several other methods need transactions and they share the same database handle so I do a commit. Any reason to set up a separate handle that doesn't require transactions?

These are basically the same method, with the exception of the method and table names. I'm thinking about switching this around to stuff the method names in a hash with the value being the table. Then, I'll create an AUTOLOAD routine that traps the name, autogenerates the method or throws an exception if the method is not found. There is no need to install the method in the symbol table as these methods are not called more than once per program run.

I am aware that this will likely slow down the performance of the program, but I was thinking that this will significantly reduce the size of the program and might make maintenance easier. There are several places where I could use this technique. Is this too trivial to really benefit from AUTOLOAD? WWMD? (What Would Monks Do?).

Cheers,
Ovid

Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.