nevdka has asked for the wisdom of the Perl Monks concerning the following question:
O wise and benevolent monks,
I have just started a new job as a Perl programmer, and have exhausted the training materials my new masters have given me, so I am seeking wisdom on my own. I come from a physics background, and the code I wrote there was far from object oriented. 'Functional' would have been generous, and maybe 'chaotic' most accurate. However, my new masters are insisting on those pesky ideas of readability, maintainability, and reliability, and use OO everywhere. I'm sure I'll be thankful once I start writing production code.
I have been creating an object model for a parking lot. My first attempt had 'Corolla' as a subclass of 'Toyota', as a Corolla was a more specific type of Toyota. However, I now realise that only the attributes are different; all the methods are the same. So, a 'Car' class would be enough:
package Car; use strict; use warnings; use Carp; sub new { my ($class) = @_; my $self = {}; bless($self, $class); return $self; } sub drive_type { my ($self, $drive) = @_; if ($drive) { unless ($drive =~ /^(?:fwd|rwd|4wd)$/) { croak "$drive not a valid drive type. Use fwd, rwd or 4wd\ +n"; } $self->{'drive'} = $drive; } return $self->{'drive'}; } sub body_type { my ($self, $body) = @_; if ($body) { unless ($body =~ /^(?:sedan|wagon|coupe|hatch)$/) { croak "$body not a valid body type. Use sedan, wagon, coup +e or hatch\n"; } $self->{'body'} = $body; } return $self->{'body'}; } sub engine_cap { my ($self, $cap) = @_; if ($cap) { $self->{'engine_cap'} = $cap; } return $self->{'engine_cap'}; } 1;
However, every Corolla will share many of its attributes with every other Corolla. Every time I create a new Corolla, I would need to set:
my $car = Car->new(); $car->drive_type('fwd'); $car->body_type('hatch'); $car->engine_cap('1798');
And whatever other attributes I put in. I would like to be able to do something like this:
my $car = Corolla->new;But that means having a subclass, which is what I want to avoid. Is there a better way to set common attributes?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Setting common object attributes
by roboticus (Chancellor) on Jul 18, 2013 at 02:45 UTC | |
by nevdka (Pilgrim) on Jul 18, 2013 at 06:05 UTC | |
|
Re: Setting common object attributes
by rjt (Curate) on Jul 18, 2013 at 02:22 UTC | |
by nevdka (Pilgrim) on Jul 18, 2013 at 04:09 UTC | |
|
Re: Setting common object attributes
by 2teez (Vicar) on Jul 18, 2013 at 03:20 UTC | |
by nevdka (Pilgrim) on Jul 18, 2013 at 23:13 UTC | |
|
Re: Setting common object attributes
by tobyink (Canon) on Jul 18, 2013 at 06:52 UTC | |
by nevdka (Pilgrim) on Jul 18, 2013 at 23:09 UTC | |
|
Re: Setting common object attributes
by Anonymous Monk on Jul 18, 2013 at 03:06 UTC | |
by Anonymous Monk on Jul 18, 2013 at 03:10 UTC | |
by nevdka (Pilgrim) on Jul 18, 2013 at 23:00 UTC |