Perl6 Object Oriented Cookbook (v0.2.1)  
Section 10: Limiting Access to Classes, Attributes, and Methods  
 
Recipe 10.1: Creating a '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)
5.00 Rating, 1 Vote  

How acceptable is the proposed solution?
  (Login to Vote)
0.00 Rating, 0 Votes  

Problem:  

You want to declare an attribute or method that is available only for use by the class that declares it: you don't want code outside of the class to be able to access it.

Solution:  

Use the is private property:

has $counter is private;

method do_something is private { ... };

Discussion:

A central tenet in object oriented programming is that code outside a class shouldn't be welcome to muck with the insides of a class unless you've given it permission to do so. The property is private specifically denies that permission, thereby creating an attribute or method which can only be accessed by code inside the current class. This is typically used for keeping track of internal state or performing other actions that users outside the class don't need to know about.

By default, has declarations are assumed to be is private, and method declarations are assumed to be is public.


Log In to Comment


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