Jonathan Rockway ha scritto:
nntp.perl.org wrote:
Hello all.
I've written a module to deal with the issue of inheritable class data
(yes, yet another one).
What's peculiar with it is that it doesn't rely on accessor methods.
After declaration, you can use the variables just like any other package
variable but you can inherit and override those variables in other
packages/classes.
I'm thinking of calling the module Package::Data::Inheritable which
should reflect the emphasis on package variables rather than on classes.

Before uploading to CPAN I would like to check whether I missed some
module that does the same and if the proposed name/namespace is good.

Not sure what you're trying to do. Is it this?

  package A;
  our $DATA = 'A';

  package B;
  use base 'A';
  our $DATA = 'B';

  package C;
  use base 'A';
And then:

  $A::DATA # 'A'
  $B::DATA # 'B'
  $C::DATA # 'A'


Yes, this is what is does (with some extra boilerplate code).

If so, I don't know of anything on CPAN that does this.  However, I
think inheriting variables is a *terrible* idea.
What is your reason for wanting to use variables instead of properly
delegating to methods?

This is common practice in other well known OO languages like C++ and
Java. In fact the module implements that very kind of class data semantic.
I'm aware that you loose encapsulation with package variables, but
convenience of use sometimes comes first to me.

A typical case I feel the need for that is when you have a hierarchy of
classes where you deal with a lot of data fields and you name them with
class data members:

    our FIELDNAME1 = 'field1';
    our FIELDNAME2 = 'field2';
    ...
    our FIELDNAMEn = 'fieldn';

and then you use them like this:

    foo({param1 => $val,
         fields => { $FIELDNAME1 => $val1,
                     $FIELDNAME2 => $val2,
                     ...
                     $FIELDNAMEn => $valn,
                    },
         });
    ...
    foreach my $field ($FIELD4, $FIELD2, ..., $FIELD10) {
    ...

With accessor methods this would be considerably more verbose:

    foo({param  => $val,
         fields => { $SomeClass->FIELDNAME1 => $val1,
                     $SomeClass->FIELDNAME2 => $val2,
                     ...
                     $SomeClass->FIELDNAMEn => $valn,
                    },
         });
    ...
foreach my $field ($SomeClass->FIELD4, $SomeClass->FIELD2, ..., $SomeClass->FIELD10) {
    ...

This becomes quickly unreadable and is not lazy.
Furthermore every fieldname access is a method call which is too much
overhead, especially when you have many fields to deal with.

regards,
Giacomo



Regards,
Jonathan Rockway

Reply via email to