in reply to OO Getters/Setters
So, the solution to this is accessing data or setting it via methods . . . I've seen a getter/setter in OO tutorials, one written for each attribute.
Yes, most tutorials do it that way. They're wrong, or at least misleading. Getter/setter methods (or for those who like fancier words, accessors/mutators) should be avoided. Sometimes you do need them on a few attributes, but if your design calls for accessors/mutators on every internal attribute, you need to rethink your design. Doing it that way won't really result in an object, but a datastructure that happens to be accessed with an object-like syntax. The only difference between this:
$obj->{field};
And this:
$obj->field();
Is some fancy syntax. I bet the second form is slower, too (haven't benchmarked it, though).
Now when you actually do need accessors/mutators . . .
Why do you need a different method for each bit of data?
True to TIMTOWTDI, Perl offers many ways of producing accessors/mutators. Your way isn't necessarily wrong. If use strict 'subs'; was useful for method lookups, then I think you can make a stronger argument against what you're doing (since a method-per-attribute way would give you compile-time errors when you make a typo). Since methods are all looked up at run time, use strict 'subs'; isn't particularly useful no matter how you do it.
One problem with your way of generating accessors/mutators is that, unless you do checking inside the method, a user can insert an attribute that didn't previously exist.
There are other ways of generating accessors/mutators. One is to use AUTOLOAD, but it's slow. Class::Accessors works by using closures, like this:
my @FIELDS = qw( a b c d ); # Put your field names here foreach my $field (@FIELDS) { no strict 'refs'; *$field = sub { my $self = shift; $self->{$field} = shift if @_; return $self->{$field}; }; }
The symbol table will make a reference to the same subroutine each time, thus saving memory. It's also as fast as any other method lookup. If you wrap the above in a BEGIN block, there will be no runtime hit for generating the methods.
----
I wanted to explore how Perl's closures can be manipulated, and ended up creating an object system by accident.
-- Schemer
: () { :|:& };:
Note: All code is untested, unless otherwise stated
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Re: OO Getters/Setters
by dreadpiratepeter (Priest) on Dec 31, 2003 at 15:04 UTC | |
by hardburn (Abbot) on Dec 31, 2003 at 15:13 UTC | |
by dreadpiratepeter (Priest) on Dec 31, 2003 at 15:29 UTC | |
by hardburn (Abbot) on Dec 31, 2003 at 15:43 UTC | |
by duff (Parson) on Dec 31, 2003 at 17:01 UTC | |
| |
by linux454 (Pilgrim) on Jan 02, 2004 at 15:56 UTC | |
| |
by flyingmoose (Priest) on Jan 03, 2004 at 15:45 UTC |