|No such thing as a small change|
Private Methods Meditationby theAcolyte (Pilgrim)
|on Jul 19, 2004 at 04:08 UTC||Need Help??|
Private Methods (as I understand them)
I imagine these methods need to know things that subclasses shouldn't/wouldn't know, or if called at the wrong time/place could mess up the object in ways that would make your head explode. Violently.
How can I make private methods? Perl has no built in contruct to make methods private and I initally thought this was a good idea. If I _really_ want to use a method you consider private I should be able to. And if it makes my program crash or sing Three Dog Night songs then, its my problem.
The ways I've found to 'fake' private methods involve using code references. I didn't come up with these ideas myself, but saw them mentioned in different posts -- well, the first one anyway. And the second is an extention of the first. I'm calling these:
Very Private Methods:
This method is only callable from within the package the subroutine is in. $object->$very_private(); won't work from wherever you actually created the object, so this fits the description of a private method. However, I'm not really thrilled with making it ~impossible~ to reach in and use it so I tried:
Private but not really private Methods:
Now we've got a method that's easy to call within the package that defines it ($self->$Semi_Private_Method();) but can also be called from outside if you REALLY want to ....
Which one to use?
So ... after all of this I decided on an old standard. Private sub names prefixed with an _ and, to prevent an inheriting class from accidently overriding a private method ... name them _packagename_subname.
I know a lot of programmers insist that you need private methods, but thats like saying 'I expect programmers using my class to be idiots'. And, well, if they're idiot, then too bad. :P