Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

lock a method or functinoality to class & subclass

by nmerriweather (Friar)
on Feb 13, 2007 at 23:32 UTC ( [id://599809]=perlquestion: print w/replies, xml ) Need Help??

nmerriweather has asked for the wisdom of the Perl Monks concerning the following question:

i have a class, and I'd like to make sure that only instances of that class - or instances of a subclass - can perform certain functions.

ie, i have a get/set function. i want anyone to be able to get, but i only want the class itself ( or a class that claims it ISA member of that class ) to be able to set.

does anyone have a suggestion?
  • Comment on lock a method or functinoality to class & subclass

Replies are listed 'Best First'.
Re: lock a method or functinoality to class & subclass
by merlyn (Sage) on Feb 13, 2007 at 23:43 UTC
    Name the method beginning with an initial underscore, which is usually an indication that it's an internal or restriction function.

    Then, either don't document it, or document it with "for friend classes only".

    Do not use force. Force doesn't work. If you don't trust other programmers, you shouldn't be programming.

Re:lock a method or functinoality to class & subclass
by Cabrion (Friar) on Feb 14, 2007 at 00:12 UTC
    I agree with Randal. I think Larry said something about livingrooms and shotguns on this topic. However, you might try something in your method like this:
    sub foo { my $self = shift; die "Get out of my class" unless ref($self); # not called as method die "Get out of my class" unless $self->isa('My::Class'); }
    Above code for illustrative purposes only. Certaily could be done a lot better/cleaner.
Re: lock a method or functinoality to class & subclass
by pgor (Beadle) on Feb 14, 2007 at 00:14 UTC

    You can do it with

    die("private method!") unless (caller())[0]->isa(__PACKAGE__);

    at the beginning of your private method, but that will add some solid overhead to your code, and I'm sure others will point out how it will break.

    Just because you can, doesn't mean you should. I recommend you follow merlyn's advice.

    pg
Re: lock a method or functinoality to class & subclass
by shonorio (Hermit) on Feb 14, 2007 at 02:18 UTC

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (4)
As of 2024-04-24 20:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found