Update: Perhaps a more appropriate title for this node is Minimizing code redundancy vs over-parameterizing
Hi,
I recently refactored a program and eliminated a lot of redundant code. Now I have a series of functions that are structured like this (simplified example):
sub foo { my ( $type ) = @_; my %data = ( type1 => { dir => 'a', text1 => 'text-a1', text2 => 'text-a2' }, type2 => { dir => 'b', text1 => 'text-b1', text2 => 'text-b2' }, ... type9 => { dir => 'i', text1 => 'text-i1', text2 => 'text-i2' } ); # do stuff with $data{$type}{dir|text1|text2} my $barresult = bar( $type ); my $bazresult = baz( $type ); } sub bar { my ( $type ) = @_; my %data = ( type1 => { url => 'a', regex => '\d\d(\d\d)(\d\d)(\d\d)' }, type2 => { url => 'b', regex => '(\d\d)(\d\d)(\d\d)' }, ... type9 => { url => 'i', regex => '\.(\d{8})\.' } ); # do stuff with $data{$type}{url} and $data{$type}{regex} } sub baz { # similar to &bar }
Initially each function was duplicated for each $type (&type1_foo, &type1_bar, &type1_baz, &type2_foo, etc) and the data now in the %data hashes were hard coded. Now the code is easier for me to read and maintain, and all the guts are hidden behind a single call to foo with only one parameter: foo( 'type1' ); However, the code portion for each function is only 20 or 30 lines, which is sometimes shorter than the %data hash that is initialized for each sub, and I am starting to feel like the subroutines are being dominated by the hashes instead of actual code.
I considered pulling all of the %data hashes out and combining them, then passing a hashref ($data{$type}), but while I think that removing the data elements from the subs they are used in will clean up the code, it will obfuscate the purpose of each data element (which would make adding new $types more difficult). I also considered converting the subs into class methods and creating instances for each $type, but for some reason that seems like overkill since all of the data elements would have to be specified as instance attributes anyway. Or should I create separate classes for each $type?
How should I structure a series of relatively short functions that each require a handful of parameters, without having to pass all the parameters around? Was I better off before refactoring? Is OO the way to go here?
Thanks!!
In reply to Structuring code by bobf
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |