|Pathologically Eclectic Rubbish Lister|
(Ovid - ref $proto $proto) Re(3): Adding autoloaded methods to symbol table with using strict refby Ovid (Cardinal)
|on Feb 26, 2002 at 21:24 UTC||Need Help??|
One of the strengths/weaknesses of Perl's OO system is the lack of a clean separation of class and instance data and methods. This typically isn't that big of a deal, but many Perl programmers have never used OO programming with another language and may not appreciate the distinction between the two.
Imagine that you are writing some sort of bank account software. In your specs, you see that if anyone has a minimum savings balance less than $100US, you stop paying interest on that account. Since this applies to all accounts, the limit of 100 dollars is class data. It doesn't apply to an individual account so much as it applies to all accounts. If you need to change the limit, you can adjust the class variable and all objects automatically pick up the new value (yes, this is a simplistic example). However, if you want to check my savings balance, you would check the instance value of my account's balance. Obviously, having my account balance be class data would not make sense.
The separation between instance and class also affects methods. The typical new() constructor is a class method. In this case, it usually doesn't impart any new information to specific instances of the object being instantiated (it might do this, though, if you were keeping track of the number of accounts). It doesn't, however, typically belong to a particular instance of an object. That usually doesn't make a sensible model.
The ref $proto || $proto construct is saying "I might call this as a class method" (a constructor of a brand new object) or "I might call this as an instance method" creating a copy or clone of an object. Those two ways of calling the method seem related, but conceptually they usually are not. If you need an instance method to create a clone, then write an instance method rather than trying to override the behavior of the constructor.
You also have to consider that other programmers may have to maintain your code. Remember that OO programming, at it's heart, is to simulate a system (the first OO language was even called "Simula"). As such, it really should model something in an intuitive fashion. That is, in my opinion, yet another reason not to confuse class and instance methods. It's relatively little work to separate those out and make a cleaner interface.
Hope that helps.
Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.