http://www.perlmonks.org?node_id=339644


in reply to Re^3: (~OT) How to measure Perl skills?
in thread How to measure Perl skills?

If you're using AUTOLOAD instead of methods like this:

sub foo { my $self = shift; $self->{foo} = shift if @_; $self->{foo}; }

Then you're breaking encapsulation. You were better off just providing a hash and a few subroutines to work on it. In a well-designed class heriachracy, you will need very few accessors/mutators (i.e., methods that directly access the internal attributes of the object). OOP purists will tell you that you need none at all, but I find that in practical code, you'll have a hard time factoring out the last few.

(I suspect the reason for this is a diminishing-returns thing. You can theoretically get rid of all accessors and mutators, but eventually the work required to do so just isn't worth it.)

This isn't the only use of AUTOLOAD, but it is almost certainly the most common.

Ignoring OO purity for the moment, AUTOLOAD still isn't the best way to get accessors/mutators, provided you know what fields you want to work with in advance (if you don't, then you'll probably have to use AUTOLOAD). Example:

foreach my $field (qw/ foo bar baz /) { no strict 'refs'; *$field = sub { my $self = shift; $self->{$field} = shift if @_; $self->{$field}; }; }

This gives you a little overhead when the module is loaded. It has the advantage of being as fast as a regular method lookup, in addition to saving memory (because it's making a reference to the same subroutine each time).

----
: () { :|:& };:

Note: All code is untested, unless otherwise stated