oop - How to write elegant perl code without ref -


help me code scenario better. let's have baseclass named "car", , 2 derived classes named "ferrari" , "chevrolet". have new class named "parkinglot", should know car operating on, customize lot-size , other attributes.

now problem. current codebase iam working on matured, , it's complete written in perl oops. "parkinglot" constructor passed car object (instantiated before this) argument. code(parking lot) uses argument, ref on object pointer find whether class "ferrari"/"chevrolet" , specific operations based on car type. example, "tip of iceberg" , these kind of code littered everywhere throughout code making more unmaintainable.

tommorow, if want add new car, parking lot should support, it's becomes nightmare check references through code , changes manually. rework code make more elegant , maintainable?

as first comment on question alluded to, want here polymorphism. let car decide how car should behave rather making parking lot keep track of behaviors of every kind of car out there. e.g., instead of this:

package car;  package ferrari; use base 'car';  package chevrolet; use base 'car';  package parkinglot;  sub add_car {   if (ref $car = 'ferrari') {     $self->park_ferrari;   } elsif (ref $car = 'chevrolet') {     $self->park_chevrolet;   } else {     die "unknown car model!";   } } 

do this:

package car;  sub park {   # park generic car }  package ferrari; use base 'car'; sub park {   # take ferrari spin before parking   $self->drive_fast;   $self->super::park; }  package chevrolet; use base 'car'; # no sub park defined, parks generic car  package parkinglot;  sub add_car {   $car->park; } 

now parkinglot needs know has car , car knows how should park, can add many new car subclasses without ever having modify parkinglot.

(note above perl-like pseudocode, not real, runnable perl code. many details deliberately omitted.)


Comments

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

html - Instapaper-like algorithm -

c# - How to execute a particular part of code asynchronously in a class -