Perl6 Object Oriented Cookbook (v0.2.1)  
Section 10: Limiting Access to Classes, Attributes, and Methods  
 
Recipe 10.5: Explicitly Declaring which Classes May Access an Otherwise Private Attribute or Method
Last Updated: Sep 8, 2003
Status: Draft
      Previous Page   Next Page

How important is this problem to you?
  (Login to Vote)
4.00 Rating, 2 Votes  

How acceptable is the proposed solution?
  (Login to Vote)
3.00 Rating, 1 Vote  

Problem:  

Your class has a private attribute or method. You want to specifically grant access to the attribute or method for a selected set of classes or subclasses, without opening access for anything else.

Solution:  

Use one of the following:

class MyClass {
    method do_something
        is private
        is public(AllowedClass1, ...)	# list of "allowed" classes
    { ... }
}

class AllowedClass1 {
    method do_something {
	    my $obj = MyClass.new;
        $obj.do_something;              # OK, is explicitly allowed by MyClass
    }
}
or
class MyClass {
    method do_something is private { ... }
}

class AllowedClass1 {
    method do_something {
        my $obj = MyClass.new;
        $obj.do_something;              # WRONG, is private
        $obj.MyClass.do_something;      # ok, if you really mean it
    }
}

Discussion:

There are two basic approaches for allowing access to an attribute or method on a class-by-class basis: declaring the allowable classes in the class the attribute or method is being declared in, or declaring those permissions in any specific subclasses.

Note that the second approach breaks the encapsulation of the object, and so the first form is greatly preferred.

Issue: Does allowing access for a given class "A" imply the same access for all subclasses of "A"?

Issue: The second approach implies the use of a privacy-breaker such as that of the last recipe, above.


Log In to Comment


Login / Edit User Info -- Copyright © 2002 Cognitivity -- Previous Page   Next Page