Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re^2: "Fields" for "Objects"

by lodin (Hermit)
on Jun 10, 2009 at 21:02 UTC ( #770455=note: print w/replies, xml ) Need Help??


in reply to Re: "Fields" for "Objects"
in thread "Fields" for "Objects"

I second stvn.

Since you know which fields are permitted when the class compiles you can generate them and get rid of AUTOLOAD. AUTOLOAD is really only needed when you do not know which methods the class will need to handle.

my @fields = qw/ name age peers /; for my $name (@fields) { my $code = sub { my $self = shift; $self->{$name} = $_[0] if @_; return $self->{$name}; }; no strict 'refs'; *$name = $code; }
Now your class acts exactly like it would have acted if you manually wrote the methods, and you pay no run-time penalties.

Note how simple the logic of the code is compared to AUTOLOAD. And the AUTOLOAD implementation will get more complicated still. Consider what happens when you

  • do $obj->can('age'),
  • refactor and create a superclass that also uses AUTOLOAD, or
  • use multiple inheritance where another class also uses AUTOLOAD.
  • (Or forget to do return if $name eq 'DESTROY';.)
A proper implementation of AUTOLOAD requires an awful lot of thinking, and still it does not buy you anything, rather the opposite, if you already know the method names.

lodin

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://770455]
help
Chatterbox?
[marto]: I'm all for that
[choroba]: Trainspotting without OV is just a half of the movie!
LanX just single handedly stopped Brexit!

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (7)
As of 2018-02-19 10:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    When it is dark outside I am happiest to see ...














    Results (262 votes). Check out past polls.

    Notices?