On 9/4/07, Giacomo Cerrai <[EMAIL PROTECTED]> wrote:
> 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.

If you put the field names into an array (or hash) then it becomes a lot easier.

      our @FIELDNAMES = ( ... );
      sub fieldnames { @FIELDNAMES };

      my %fields;
      my @names = $SomeClass->fieldnames();
      @[EMAIL PROTECTED] = ($val1, $val2, ..., $valn);
      foo({param1 => $val, fields => \%fields );
      ...
      foreach my $field (@{$SomeClass->fieldnames()}) {
      ...

Reply via email to