sub name {
my $self = shift;
return $self->{name};
}
then in your other methods in the class, go ahead and use the accessor directly, with
sub foo {
my $self = shift;
print $self->name;
}
instead of
sub foo {
my $self = shift;
print $self->{name};
}
There are a number of reasons for this, and you don't have to be a Java object purist to appreciate them:
Heck, accessors can even reduce punctuation: $user->name vs. $user->{name}.
There is only one reason to not use your own accessor methods, and that's to microoptimize your code for speed. If you've gone ahead and profiled your code, say, with Devel::DProf, and you know that calls to your accessors are causing a significant slowdown from overhead, and you've eliminated other sources of speedup, and you comment your code explaining WHY you're using the attributes directly, then sure, go ahead. We had to do this in MARC::Record in some tight-loop intensive code, but even then we changed some internal representations that bypassed the accessors entirely to get even more speedup.
Agreed! (Score:1)
I've recently changed over to doing this in my own code and it's quite nice. You can really tell how complex a method is by how many accessor methods you need to call on it.
At the very least (Score:3, Insightful)
At the very least, write good tests for all your public methods. Then, when you are finally coerced into changing your attribute accesses into method calls as Andy describes (and you will if any of the following is true: your code lives long enough, your code grows large enough, or your code passes through enough maintainers), making the change will be much quicker, easier, and reliable due to the confidence you receive from being able to run the tests and say "It runs exactly like it did before I did that global search and replace."
Effective unit testing reduces the cost of change.
J. David works really hard, has a passion for writing good software, and knows many of the world's best Perl programmers
Reply to This
But Be Careful (Score:2)
Unfortunately we didn't bless the hash reference into the object until the end of the constructor so none of the accessor calls worked.
What started off as a demonstration of why using accessors is a good idea turned into a demonstration of why unit tests are essential before doing any refactoring