|No such thing as a small change|
Perl Privviesby tlm (Prior)
|on Jul 16, 2006 at 18:12 UTC||Need Help??|
Perl's OO model famously (or notoriously) provides no support for private methods. One common way to achieve method privacy is to use "lexical methods":
This enforces privacy, all right! If anything it does it too well, since $private is not accessible even to external test programs. But then, something similar is true for private methods in other languages...
Anyway, here's an alternative that is less watertight but offers greater flexibility:
Granted, it is relatively easy to circumvent this little subterfuge with another one; just replace the external call to restricted with the first line below:
At this point the subterfuge race can escalate with
But I figure that if one feels the need to push this approach this far one may as well stay with the lexical private method described earlier. I prefer the second-to-last version, even though it can be easily circumvented, or rather, because it is easy to circumvent (which is useful during testing). I see it more as an extension of the docs than as a programmatic way to enforce privacy.
I don't recall this caller-based technique to enforce privacy as being used much, which makes me wonder if there are problems with it that I'm missing. Of course, many people, myself included, often find that naming conventions (e.g. the trusty leading underscore) are sufficient reminder of which methods are not meant to be used externally. The simple rule is something like "don't call anything that is not documented". This rule works well most of the time, but it is too restrictive in some cases. For example, it is very helpful to be able to invoke private methods when testing the public ones. But, especially in larger projects, I find that some private methods are more dangerous to call externally than others, and as the complexity of naming schemes increases, it becomes easier to lose track of what the various conventions mean. In such situations, an explicit check for potentially dangerous usage seems in order.
As always, I eagerly await your thoughts and comments.
the lowliest monk