Welcome to PerlMonks (and to Perl)!
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;
I would agree, it doesn't seem to make sense to subclass in this case, since you are just setting a few attributes.
But if you're really typing my $car = Corolla->new; in your code enough times to care about how repetitive it is, there's probably a more fundamental design issue. Hence, the first part of this reply will have little to do with Perl. When do you instantiate objects? In response to what input? Where does the data come from? (I.e., what's your storage layer--database, spreadsheet, flat file, ...)
The point is, you should have a very small number of places in your code where you instantiate a Car, and you definitely shouldn't have to hard-code a new Corolla vs. a new Toyota; you should get all of the pertinent attributes from your storage layer.
Now, how to avoid repetition of data really becomes a database design question. (Even if you don't use a database, the same principles will be helpful). Have a look at database normalization (Wikipedia) for the gory details, but basically the idea is to partition the columns (attributes) into logically discrete tables. For example, you would have a table with one row for each car in the lot, but that table would only contain the owner (probably an ID, mapping to an Owner table), maybe the color, and a unique identifier for the car, which maps to a Car table with one row for each unique Make/Model/Year you care about. It's that table where 'generic' things like the engine size would be set.
Back to objects, it's common to have a different class for each table, although Perl can handle the foreign keys for you, so you can enjoy syntax about as concise as if you had one monolithic object (but without the headache of repeating yourself that you describe!)
If you are using any kind of storage that DBI can deal with (and even if you're not; this may change your mind), see DBIx::Class or Class::DBI for two ways to automate much of the class creation.
Hope this helps. This is far from a complete class on OO and DB design, but hopefully I've included enough keywords you can Google to fill in whatever prerequisite knowledge you need to get started.
In reply to Re: Setting common object attributes
by rjt
in thread Setting common object attributes
by nevdka
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |