Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: Private Class Methods

by dragonchild (Archbishop)
on Apr 05, 2002 at 18:50 UTC ( [id://157023]=note: print w/replies, xml ) Need Help??


in reply to Private Class Methods

Method calls bypass Exporter, so no, this won't work.

There are several ways to do "private" methods.

  1. The standard way is to not bother enforcing private-ness. Just pre-pend an underscore (_) to your method names and let the user consciously make the choice to violate encapsulation.
  2. You can put a
    sub _my_private_method { my $self = shift; die "Private method, jerk!" unless UNIVERSAL::isa($self, __PACKAGE__); # ... Continue on here as normal }
    That's known as a gatekeeper. I haven't seen that a lot. That kind of private allows inheritance to work. The other way, requiring that you must be of that class and that class alone would be to do something like ref $self eq __PACKAGE__, more akin to C++'s private.
  3. This applies more to data, but you can change your reference from a hashref to a coderef, effectively making all your object instances closures. This would make all your data private. You could extend it to methods, I suppose. I wouldn't reccomend it because it's extremely non-standard and would be very hard to maintain. There's also a minor speed hit, but it's not that major.
All in all, the best method I've found is #1. Just trust your users. It's the easiest policy to implement.

------
We are the carpenters and bricklayers of the Information Age.

Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.

Replies are listed 'Best First'.
Re: Re: Private Class Methods
by perrin (Chancellor) on Apr 05, 2002 at 21:43 UTC
    ++ on #1. Don't waste your time on things like this. Name it _foo() and be done with it.
Re: Re: Private Class Methods
by RMGir (Prior) on Apr 06, 2002 at 14:27 UTC
    ++ on #1.

    But #2 will fail on "indirect" private calls, i.e. where class A implements

    sub public_method { # do something $self->_my_private_method(); # do something else }
    and then public_method is invoked on a derived object. Bad bad.
    --
    Mike

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://157023]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (6)
As of 2024-04-18 19:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found