Instance Specialization

pdcawley on 2002-03-22T09:11:15

So, I was thinking about this (per object overrides of methods) on the train this morning. The 'traditional' way to specialize an object in perl is to generate a new class name for each specialized object, set its @ISA to the class of the object being specialized, and bless the object into the new class.

And it works. Sort of. The problem is that it can leak memory more and more classes get created and their instances get destroyed leaving entire symbol tables lying around orphaned. The naive approach is to shove a DESTROY method into the specialized class, but that's no good if you're specializing the object in order to add your own DESTROY behaviour.

So, wouldn't it be great if you could do this:

# Specialize takes a hash of method names and 
# subroutines
sub specialize {
  my $self = shift;
  my %method = @_;

my $syte = {} $syte->{ISA} = gensym; *{$syte->{ISA}} = [ ref($self) ];

foreach my $key (keys %method) { $syte->{$key} = gensym; *{$syte->{$key}} = $method{$key}; } bless $self, $syte; }
In other words, one could create classes that are blessed with anonymous symbol tables. Because the symbol table is anonymous it will be garbage collected by the system when the specialized object goes out of scope.

Right now, even if Perl allowed you to do this (and do you know, I've not actually checked), it's not all that useful because of issues with SUPER being determined at compile time so your specialized methods can't do 'SUPER::foo' because that'll end up searching in the parent class of the class in which they were compiled, which is not what you want.

Hmm... I wonder how hard it would be to add to Perl.


Instances

TorgoX on 2002-03-22T22:09:57

I bet you could manage to do this via a class like Class::Classless, and have /all/ specialized objects belong to your special class, and have it not be ISA anything. Then your dispatcher (in can/AUTOLOAD) would look for a method in the object, then in the classes that the object is specially tagged as belonging to. Make sense?

Re:Instances

pdcawley on 2002-03-22T22:57:47

Having taken a closer look at Class::Classless (nice work there btw), I'm sure that that approach could be made to work, but:
  1. AFAICT it'll only work for blessed hashes, and I'm not even sure it'd work that well with them.
  2. Even assuming you're happy with nothing but blessed hashes, I'm not entirely sure it'd be possible to write a UNIVERSAL::specialize that would allow you to lazily specialize any object you like.
  3. An anonymous symbol table approach would almost certainly be substantially faster.

Of course, Class::Classless has the enormous advantage of actually existing.

Which is definitely a big advantage.

I like anonymous symbol tables as an idea though. I'm sure there's lots more that could be done with them than just specialized objects. Blessed symbol tables anyone?