in reply to '100 elsif's vs hash of coderef's

or skip the dispatch hash altogether and instead dispatch by name:

use strict; use warnings; for my $name (qw(Title Description Object Properties Value Wibble)) { my $code = main->can("do$name"); if (!$code) { print "!!! Missing handler for '$name'\n"; next; } $code->(); } sub doTitle { print "Title handler\n" } sub doDescription { print "Description handler\n" } sub doObject { print "Object handler\n" } sub doProperties { print "Properties handler\n" } sub doValue { print "Value handler\n" }

Prints:

Title handler Description handler Object handler Properties handler Value handler !!! Missing handler for 'Wibble'

Now if you need a new handler all you do is add the sub.

Premature optimization is the root of all job security

Replies are listed 'Best First'.
Re^2: '100 elsif's vs hash of coderef's
by AnomalousMonk (Archbishop) on Dec 10, 2015 at 23:03 UTC

    I think I would put the dispatched functions in a separate namespace:

    c:\@Work\Perl>perl -wMstrict -le "my @args = qw(hi there); ;; for my $do_this (qw(Title Description Object Fooble Properties)) { my $code = Dispatcher->can($do_this); ;; if (!$code) { print qq{Missing Handler for '$do_this'}; next; } ;; $code->(@args); } ;; { package Dispatcher; ;; sub Title { print qq{title handler: @_}; } sub Description { print qq{description handler: @_}; } sub Object { print qq{object handler: @_}; } sub Properties { print qq{properties handler: @_}; } } " title handler: hi there description handler: hi there object handler: hi there Missing Handler for 'Fooble' properties handler: hi there
    It's no longer necessary to munge the function names, and the functions are easily factored out to a separate module (which could, of course, also be done with the original approach).


    Give a man a fish:  <%-{-{-{-<

      For "real" code my handlers are generally member functions so the "factored out" bit has already happened, but the munging is required to avoid accidental or naughty access to other members of the object.

      A sometimes benefit of munging is that several handlers can be provided for the same base name - an action method and a help string method for example, or a parser and an executor.

      Premature optimization is the root of all job security
        ... munging is required to avoid accidental or naughty access to other members of the object. [Or] several handlers can be provided for the same base name - an action method and a help string method for example ...

        An interesting approach.


        Give a man a fish:  <%-{-{-{-<