[Chicago-talk] A question of style: Class::Accessor

Andy Lester andy at petdance.com
Sun Nov 23 21:09:59 CST 2003

> except, I'm still inside the class.  I'd use the methods, from outside 
> the
> class

I understand that you're still inside the class.  I still strongly 
suggest that you use the accessors that you've provided.

1) What if you have $user->name() and inside the class you use 
$user->{name} but somewhere down the road you do some manipulation with 
$user->{name} inside $user->name()?  Say you want it to return a 
proper-cased string?  Now you're going to either replicate that code to 
proper-case the string, or you're going to go and change your 
$user->{name} to $user->name anyway.

2) If you use your accessor methods, then you're effectively testing 
them out.  What if your accessor is broken somehow?  You'll never know.

3) You're tying your code to the specific implementation of your 
object.  Objects don't have to be hashes: Maybe you want to use an 
array, like in WWW::Mechanize::Link.

4) Maybe you want to change the internal naming convention.  You 
shouldn't have to go retrofit your code to do so.

There is only one reason to not use the accessor methods, and that's 
because for some reason you're microoptimizing your code for speed and 
you can't afford the function calls.  If you've gone ahead and profiled 
your code, say, with Devel::DProf, and you know that calls to your 
accessors are causing a slowdown, 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.

Heck, accessors can even be clearer: $user->name vs. $user->{name}.


Andy Lester
andy at petdance.com, AIM:petdance
http://petdance.com/ http://use.perl.org/~petdance/

More information about the Chicago-talk mailing list