Classes as objects

Ovid on 2002-12-30T18:47:47

Due to some feedback received here, I have stopped my work on developing persistent objects and switched to Class::DBI. My only significant problem with Class::DBI is that method names default to the field names. I prefer that they be decoupled so that I can change field names without having to change the code in many places. To get around that, I was doing some work with base classes and symbolic references to ensure that I was setting up accessor and mutator names correctly, but this was using package variables and violating encapsulation, so I wasn't happy with that, either. Finally, after discussing the problem with a friend, the solution became clear. I turned the classes into objects and call methods on them. This has improved encapsulation and automatically meshes nicely with Class::DBI's methods of creating proper accessor and mutator names.

package Foo::SaleItem;
use base 'Foo::Class';
use strict;
use warnings;

my $map = {
    sale_id       => 'sale',
    sku           => 'sku',
    quantity      => 'quantity',
    actual_price  => 'actualPrice',
    applied_price => 'appliedPrice'
};

my $data = {
    id     => 'sale_item_id',
    fields => $map,
};

my $class = __PACKAGE__->initialize( $data );
$class->table('sale_item');
$class->columns( All => $class->get_fields );

1;

The great thing about that is the following line:

my $class = __PACKAGE__->initialize( $data );

That sets up all of my class data and creates the accessor and mutator names for the subclass, all without any extra work on the part of the programmer. I understand that Ruby and SmallTalk both treat classes as objects and I'm curious to see what they do with them. It saved me a lot of work.

Update: The other benefit is that class data is stored in one and only one place. That's one thing that always bugged me about Perl -- having five or six different objects, all of whom carry around copies of the class data.