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


in reply to A question of style: Composite keys to multiple values

Hide the complexity behind an interface.
package My::FieldMap; our %INTERNAL_VALUES = ( 'foo|bar' => 'fb_val' ); our %INTERNAL_NAMES = ( 'foo|bar' => 'fb_val' ); sub _build_key { return lc( join '|', @_); } sub get_internal_name_value { shift if $_[0] eq __PACKAGE__; # Can call as pkg method my $ext_name = shift; my $ext_value = shift; my $composite_key = _build_key( $ext_name, $ext_value ); # probably want to put some error checking code here. # What do you do if called in scalar context? # What if one or both keys don't exist? return ( $INTERNAL_NAMES{$composite_key}, $INTERNAL_VALUES{$composite_key} ); }

Use it like this:

my ($in,$iv) = My::FieldMap->get_internal_name_value( $ext_name, $ext_ +value ); # or my ($in,$iv) = My::FieldMap::get_internal_name_value( $ext_name, $ext_ +value );

Now, when you have to deal with millions of field/name pairs, and you move to Redis or memcached to store them, you just have to update the lookup function.

A good interface with horrible code behind it is 10000% better than the most elegant snippets sprinkled everywhere.


TGI says moo

Replies are listed 'Best First'.
Re^2: A question of style: Composite keys to multiple values
by Voronich (Hermit) on Aug 07, 2012 at 17:39 UTC

    Yep. I like the idea. It "seems" heavyhanded at first blush. But the benefit on the aesthetics of the client side code would be marked.

    I expect it won't grow past an absolute outer bound of a few hundred k pairsets. By then the thing to do would be to migrate all of it into stored procs (along with a couple levels farther out so it's all internal to the database.)

    But I'll burn that bridge when I get to it.