You are on the right path. When you have a bunch of if/else statements on a single variable, it is sometimes appropriate to ask if polymorphism would help.
if ($act eq 'open_file'){ #stuff; } elsif ( $act eq 'open_stuff') { # stuff; } elsif ( $act eq 'speak' ) { # stuff; }
The problem with the above code is that it's more likely to have a bug (what if you forget to add a new action?) and it can be cumbersome to read. How about creating a factory that returns an object that's been blessed into the appropriate class, based upon the value of $act?
package My::Actions; use Carp; sub factory { my ($class, $action) = @_; my %actions = ( open_file => 'My::Actions::OpenFile', open_stuff => 'My::Actions::OpenStuff', speak => 'My::Actions::Speak' ); croak "Unknown action ($action)" unless exists $actions{$action}; my $class = $actions{$action}; return $class->new; } sub do_stuff { my $class = shift; croak "Class ($class) did not implement do_stuff()"; }
In the above snippet, all of the classes in the %actions hash inherit from My::Actions and should have a do_stuff() method (see snippet below).
use My::Actions; my $object = My::Actions->factory($act); $object->do_stuff;
In the above code, the do_stuff() method will croak if you forgot to create it, otherwise your generated objects can now do what you want without the cumbersome if/else logic. Further, by merely creating a new class when a new action is required (and adding it to the factory hash), your main code does not need to change.
The only caveat that I have is that I you need to analyze your code to figure out if a factory pattern is warranted and fits your object model. Factories can be fun and solve thorny problems. They can also create a confusing mess when not used correctly.
... and in retrospect, I kind of think I wasn't quite answering your question ...
Cheers,
Ovid
New address of my CGI Course.
Silence is Evil (feel free to copy and distribute widely - note copyright text)
In reply to Re: OO/Application Framework question
by Ovid
in thread OO/Application Framework question
by joeblow
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |