develooper Front page | perl.fwp | Postings from December 2007

bad code to good golf

Thread Next
Uri Guttman
December 8, 2007 22:43
bad code to good golf
Message ID:

i have had the pleasure of doing code review for a client and finding
this gem:

sub new {
    my $class   = shift;
    my %params  = (@_);
    my $self    = {};
    my $package = caller();
    for my $key ( keys %params ) {
        $self->{$key} = $params{$key};
    bless( $self, $class );
    return $self;

even better than just be a poorly written constructor is that it is
inside a 'factory' module that is inherited by 80 other modules!!

so i quickly rewrote it and the new sub doubled in speed. i can't run
the whole system so i can't yet tell how much improvement would be seen
there. but consider that this is call all over by every other module, i
suspect some noticeable speedups.

anyhow you have two challenges, if you desire. the first is very easy
but amusing when compared to the original code. rewrite that sub (a
minimal constructor that takes a key/value list and makes a hash based
object with no extra checking or work) with the shortest but cleanest
and clear code you can.

i have a clean 2 line version that would be understood by almost
anyone. it was the one i benchmarked against the original.

your second challenge is to golf the same constructor. the char count
will be between the {} of the sub body as the name and 'sub' are

i have two solutions of 33 and 24 chars so you have to beat those. the
longer one is amusing enough to show it later.

doing these reviews of large and mediocre code bases gives me access to
all sorts of bad code. would it be fun to post more snippets and taunt
them with happy fun ball?


Uri Guttman  ------  --------
--Perl Consulting, Stem Development, Systems Architecture, Design and Coding-
Search or Offer Perl Jobs  ----------------------------

Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About