in reply to How treat query elegantly and more?

Dispatch table?
my %query_builders = ( a => \&a_query_builder, b => \&b_query_builder, ); $query_builders{$query_name}->();

Replies are listed 'Best First'.
Re^2: How treat query elegantly and more?
by xiaoyafeng (Deacon) on Jul 01, 2010 at 04:50 UTC

    Thanks for your reply!

    but dispatch table seems not to shorten code. I still have to write a_query,b_query,c_query... respectly. In my brain, a_query_builder, b_query_builder ... and x_query_builder sub are all much similar like:
    sub a_query_builder{ my ($table_name, $display_cols_ref, $where_cols_ref) = @_; if ($where_cols_ref->{'year_min'}) { push @clauses, "Year >= $wher +e_cols_ref->{'year_min'}" } if ($where_cols_ref->{'year_max'}) { push @clauses, "Year <= $wher +e_cols_ref->{'year_max'}" } # ... $clause = join(" AND ", @clauses); $display_cols = join(",", @$display_cols_ref); $sth = $dbh->prepare("SELECT $display_cols FROM $table_name WHERE $cla +use"); }

    I'm not sure the above treatment correct or not, but I hope to create a general code to handle all kinds of query statement building. Is creating a query class a good idea?





    I am trying to improve my English skills, if you see a mistake please feel free to reply or /msg me a correction

      but dispatch table seems not to shorten code.

      The only code that could be shortened was hidden as "...".

      What the dispatch tables provide is an elegant way of breaking down your unmanageably long function into smaller blocks.