oop - Perl is polymorphism worth it? -
there seem number of ways polymorphism in perl feel "hacky" me. i'm new perl interpreting wrong find examples make code illegible , controversial.
say have widget class contains data , methods widgets need. there handful of widget types (i.e. calender, schedule, etc). , need communicate each other (via parent container class).
would playing namespace , making widget prototype worth it?
should give each widget reference object (one of types) @ instantiation?
forget types being objects , make widget large class few methods used per instance based on type set. else?
i come c/c++ background , i'm finding difficult decide on perl programming model.
also, i'm don't have strong type safety or private member requirements. project mid sized web app couple developers , portability other projects isn't priority. easy extensibilty without needing decipher perl hacks useful though.
the "modern perl" approach define widget
role. role can thought of similar mixin, interface, or abstract base class. moose::role or 1 of more light-weight alternatives (moo::role, role::tiny).
{ package widget; use moo::role; sub some_common_method { $self = shift; ...; } sub another_common_method { $self = shift; ...; } # here we're indicating widgets must # have method called yet_another_common_method, # we're not defining how method should # implemented. requires "yet_another_common_method"; }
now can create class composes role:
{ package calendar; use moo; "widget"; # here's member variable. has year => (is => "ro", required => 1); # widget requires implement this. sub yet_another_common_method { $self = shift; ...; } # can override widget's implementation # of method. sub some_common_method { $self = shift; ...; } # can install hooks ("method modifiers") # widget's methods. before another_common_method => sub { $self = shift; print stderr "calendar ", $self->year, ": another_common_method() called.\n"; }; }
and another:
{ package schedule; use moo; "widget", "editable"; sub yet_another_common_method { $self = shift; ...; } }
and use classes:
my $calendar = calendar->new( year => 2014 ); $schedule = schedule->new; @widgets = ($calendar, $schedule); (@widgets) { $_->some_common_method if $_->does('widget'); }
Comments
Post a Comment