Syntactic Confectionery Delight | |
PerlMonks |
Re: Common sub as method or function (or)by tye (Sage) |
on Aug 15, 2007 at 17:32 UTC ( [id://632806]=note: print w/replies, xml ) | Need Help?? |
You can compile the code for methods in a package other than the one used to look up methods (the one matching the class name), then you can put non-method utilities in that non-class package and use them directly w/o inheritance and without poluting your "method name" namespace.
Then you don't have to try to guess whether the first argument is an object or not. Perhaps more importantly, you don't have to worry about your users being confused when they access a utility function that has nothing to do with the object via a simple $obj->_timestamp(), since that would tell them that there is no _timestamp() method. If you don't like the underscore, then you can list which methods to export rather than just exporting all subroutines that don't have a leading underscore. Just because Perl 5 doesn't include a feature for distinguishing methods from non-methods, doesn't mean you have to throw all of those different items into the same namespace. Note that this breaks SUPER:: and some naive OO doohickeys that try to rely on caller (which doesn't currently provide a proper class name for such uses). If you want your users to be able to access the util sub as a method, then you can use this same technique (of compiling methods into a package other than the one having the name of the class) to provide both a method and non-method version without having to try to guess whether the first argument is an object:
- tye
In Section
Seekers of Perl Wisdom
|
|