Install Perl 5.8.8
[msysgit.git] / mingw / html / pod / perltooc.html
blobe07f6b919920eb3356d7339408532ed9b24338c6
1 <?xml version="1.0" ?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3 <html xmlns="http://www.w3.org/1999/xhtml">
4 <head>
5 <title>perltooc - Tom's OO Tutorial for Class Data in Perl</title>
6 <meta http-equiv="content-type" content="text/html; charset=utf-8" />
7 <link rev="made" href="mailto:" />
8 </head>
10 <body style="background-color: white">
11 <table border="0" width="100%" cellspacing="0" cellpadding="3">
12 <tr><td class="block" style="background-color: #cccccc" valign="middle">
13 <big><strong><span class="block">&nbsp;perltooc - Tom's OO Tutorial for Class Data in Perl</span></strong></big>
14 </td></tr>
15 </table>
17 <p><a name="__index__"></a></p>
18 <!-- INDEX BEGIN -->
20 <ul>
22 <li><a href="#name">NAME</a></li>
23 <li><a href="#description">DESCRIPTION</a></li>
24 <li><a href="#class_data_in_a_can">Class Data in a Can</a></li>
25 <li><a href="#class_data_as_package_variables">Class Data as Package Variables</a></li>
26 <ul>
28 <li><a href="#putting_all_your_eggs_in_one_basket">Putting All Your Eggs in One Basket</a></li>
29 <li><a href="#inheritance_concerns">Inheritance Concerns</a></li>
30 <li><a href="#the_eponymous_metaobject">The Eponymous Meta-Object</a></li>
31 <li><a href="#indirect_references_to_class_data">Indirect References to Class Data</a></li>
32 <li><a href="#monadic_classes">Monadic Classes</a></li>
33 <li><a href="#translucent_attributes">Translucent Attributes</a></li>
34 </ul>
36 <li><a href="#class_data_as_lexical_variables">Class Data as Lexical Variables</a></li>
37 <ul>
39 <li><a href="#privacy_and_responsibility">Privacy and Responsibility</a></li>
40 <li><a href="#filescoped_lexicals">File-Scoped Lexicals</a></li>
41 <li><a href="#more_inheritance_concerns">More Inheritance Concerns</a></li>
42 <li><a href="#locking_the_door_and_throwing_away_the_key">Locking the Door and Throwing Away the Key</a></li>
43 <li><a href="#translucency_revisited">Translucency Revisited</a></li>
44 </ul>
46 <li><a href="#notes">NOTES</a></li>
47 <li><a href="#see_also">SEE ALSO</a></li>
48 <li><a href="#author_and_copyright">AUTHOR AND COPYRIGHT</a></li>
49 <li><a href="#acknowledgements">ACKNOWLEDGEMENTS</a></li>
50 <li><a href="#history">HISTORY</a></li>
51 </ul>
52 <!-- INDEX END -->
54 <hr />
55 <p>
56 </p>
57 <h1><a name="name">NAME</a></h1>
58 <p>perltooc - Tom's OO Tutorial for Class Data in Perl</p>
59 <p>
60 </p>
61 <hr />
62 <h1><a name="description">DESCRIPTION</a></h1>
63 <p>When designing an object class, you are sometimes faced with the situation
64 of wanting common state shared by all objects of that class.
65 Such <em>class attributes</em> act somewhat like global variables for the entire
66 class, but unlike program-wide globals, class attributes have meaning only to
67 the class itself.</p>
68 <p>Here are a few examples where class attributes might come in handy:</p>
69 <ul>
70 <li>
71 <p>to keep a count of the objects you've created, or how many are
72 still extant.</p>
73 </li>
74 <li>
75 <p>to extract the name or file descriptor for a logfile used by a debugging
76 method.</p>
77 </li>
78 <li>
79 <p>to access collective data, like the total amount of cash dispensed by
80 all ATMs in a network in a given day.</p>
81 </li>
82 <li>
83 <p>to access the last object created by a class, or the most accessed object,
84 or to retrieve a list of all objects.</p>
85 </li>
86 </ul>
87 <p>Unlike a true global, class attributes should not be accessed directly.
88 Instead, their state should be inspected, and perhaps altered, only
89 through the mediated access of <em>class methods</em>. These class attributes
90 accessor methods are similar in spirit and function to accessors used
91 to manipulate the state of instance attributes on an object. They provide a
92 clear firewall between interface and implementation.</p>
93 <p>You should allow access to class attributes through either the class
94 name or any object of that class. If we assume that $an_object is of
95 type Some_Class, and the &amp;Some_Class::population_count method accesses
96 class attributes, then these two invocations should both be possible,
97 and almost certainly equivalent.</p>
98 <pre>
99 Some_Class-&gt;population_count()
100 $an_object-&gt;population_count()</pre>
101 <p>The question is, where do you store the state which that method accesses?
102 Unlike more restrictive languages like C++, where these are called
103 static data members, Perl provides no syntactic mechanism to declare
104 class attributes, any more than it provides a syntactic mechanism to
105 declare instance attributes. Perl provides the developer with a broad
106 set of powerful but flexible features that can be uniquely crafted to
107 the particular demands of the situation.</p>
108 <p>A class in Perl is typically implemented in a module. A module consists
109 of two complementary feature sets: a package for interfacing with the
110 outside world, and a lexical file scope for privacy. Either of these
111 two mechanisms can be used to implement class attributes. That means you
112 get to decide whether to put your class attributes in package variables
113 or to put them in lexical variables.</p>
114 <p>And those aren't the only decisions to make. If you choose to use package
115 variables, you can make your class attribute accessor methods either ignorant
116 of inheritance or sensitive to it. If you choose lexical variables,
117 you can elect to permit access to them from anywhere in the entire file
118 scope, or you can limit direct data access exclusively to the methods
119 implementing those attributes.</p>
121 </p>
122 <hr />
123 <h1><a name="class_data_in_a_can">Class Data in a Can</a></h1>
124 <p>One of the easiest ways to solve a hard problem is to let someone else
125 do it for you! In this case, Class::Data::Inheritable (available on a
126 CPAN near you) offers a canned solution to the class data problem
127 using closures. So before you wade into this document, consider
128 having a look at that module.</p>
130 </p>
131 <hr />
132 <h1><a name="class_data_as_package_variables">Class Data as Package Variables</a></h1>
133 <p>Because a class in Perl is really just a package, using package variables
134 to hold class attributes is the most natural choice. This makes it simple
135 for each class to have its own class attributes. Let's say you have a class
136 called Some_Class that needs a couple of different attributes that you'd
137 like to be global to the entire class. The simplest thing to do is to
138 use package variables like $Some_Class::CData1 and $Some_Class::CData2
139 to hold these attributes. But we certainly don't want to encourage
140 outsiders to touch those data directly, so we provide methods
141 to mediate access.</p>
142 <p>In the accessor methods below, we'll for now just ignore the first
143 argument--that part to the left of the arrow on method invocation, which
144 is either a class name or an object reference.</p>
145 <pre>
146 package Some_Class;
147 sub CData1 {
148 shift; # XXX: ignore calling class/object
149 $Some_Class::CData1 = shift if @_;
150 return $Some_Class::CData1;
152 sub CData2 {
153 shift; # XXX: ignore calling class/object
154 $Some_Class::CData2 = shift if @_;
155 return $Some_Class::CData2;
156 }</pre>
157 <p>This technique is highly legible and should be completely straightforward
158 to even the novice Perl programmer. By fully qualifying the package
159 variables, they stand out clearly when reading the code. Unfortunately,
160 if you misspell one of these, you've introduced an error that's hard
161 to catch. It's also somewhat disconcerting to see the class name itself
162 hard-coded in so many places.</p>
163 <p>Both these problems can be easily fixed. Just add the <code>use strict</code>
164 pragma, then pre-declare your package variables. (The <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_our"><code>our</code></a> operator
165 will be new in 5.6, and will work for package globals just like <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_my"><code>my</code></a>
166 works for scoped lexicals.)</p>
167 <pre>
168 package Some_Class;
169 use strict;
170 our($CData1, $CData2); # our() is new to perl5.6
171 sub CData1 {
172 shift; # XXX: ignore calling class/object
173 $CData1 = shift if @_;
174 return $CData1;
176 sub CData2 {
177 shift; # XXX: ignore calling class/object
178 $CData2 = shift if @_;
179 return $CData2;
180 }</pre>
181 <p>As with any other global variable, some programmers prefer to start their
182 package variables with capital letters. This helps clarity somewhat, but
183 by no longer fully qualifying the package variables, their significance
184 can be lost when reading the code. You can fix this easily enough by
185 choosing better names than were used here.</p>
187 </p>
188 <h2><a name="putting_all_your_eggs_in_one_basket">Putting All Your Eggs in One Basket</a></h2>
189 <p>Just as the mindless enumeration of accessor methods for instance attributes
190 grows tedious after the first few (see <a href="file://C|\msysgit\mingw\html/pod/perltoot.html">the perltoot manpage</a>), so too does the
191 repetition begin to grate when listing out accessor methods for class
192 data. Repetition runs counter to the primary virtue of a programmer:
193 Laziness, here manifesting as that innate urge every programmer feels
194 to factor out duplicate code whenever possible.</p>
195 <p>Here's what to do. First, make just one hash to hold all class attributes.</p>
196 <pre>
197 package Some_Class;
198 use strict;
199 our %ClassData = ( # our() is new to perl5.6
200 CData1 =&gt; &quot;&quot;,
201 CData2 =&gt; &quot;&quot;,
202 );</pre>
203 <p>Using closures (see <a href="file://C|\msysgit\mingw\html/pod/perlref.html">the perlref manpage</a>) and direct access to the package symbol
204 table (see <a href="file://C|\msysgit\mingw\html/pod/perlmod.html">the perlmod manpage</a>), now clone an accessor method for each key in
205 the %ClassData hash. Each of these methods is used to fetch or store
206 values to the specific, named class attribute.</p>
207 <pre>
208 for my $datum (keys %ClassData) {
209 no strict &quot;refs&quot;; # to register new methods in package
210 *$datum = sub {
211 shift; # XXX: ignore calling class/object
212 $ClassData{$datum} = shift if @_;
213 return $ClassData{$datum};
215 }</pre>
216 <p>It's true that you could work out a solution employing an &amp;AUTOLOAD
217 method, but this approach is unlikely to prove satisfactory. Your
218 function would have to distinguish between class attributes and object
219 attributes; it could interfere with inheritance; and it would have to
220 careful about DESTROY. Such complexity is uncalled for in most cases,
221 and certainly in this one.</p>
222 <p>You may wonder why we're rescinding strict refs for the loop. We're
223 manipulating the package's symbol table to introduce new function names
224 using symbolic references (indirect naming), which the strict pragma
225 would otherwise forbid. Normally, symbolic references are a dodgy
226 notion at best. This isn't just because they can be used accidentally
227 when you aren't meaning to. It's also because for most uses
228 to which beginning Perl programmers attempt to put symbolic references,
229 we have much better approaches, like nested hashes or hashes of arrays.
230 But there's nothing wrong with using symbolic references to manipulate
231 something that is meaningful only from the perspective of the package
232 symbol table, like method names or package variables. In other
233 words, when you want to refer to the symbol table, use symbol references.</p>
234 <p>Clustering all the class attributes in one place has several advantages.
235 They're easy to spot, initialize, and change. The aggregation also
236 makes them convenient to access externally, such as from a debugger
237 or a persistence package. The only possible problem is that we don't
238 automatically know the name of each class's class object, should it have
239 one. This issue is addressed below in <a href="#the_eponymous_metaobject">The Eponymous Meta-Object</a>.</p>
241 </p>
242 <h2><a name="inheritance_concerns">Inheritance Concerns</a></h2>
243 <p>Suppose you have an instance of a derived class, and you access class
244 data using an inherited method call. Should that end up referring
245 to the base class's attributes, or to those in the derived class?
246 How would it work in the earlier examples? The derived class inherits
247 all the base class's methods, including those that access class attributes.
248 But what package are the class attributes stored in?</p>
249 <p>The answer is that, as written, class attributes are stored in the package into
250 which those methods were compiled. When you invoke the &amp;CData1 method
251 on the name of the derived class or on one of that class's objects, the
252 version shown above is still run, so you'll access $Some_Class::CData1--or
253 in the method cloning version, <code>$Some_Class::ClassData{CData1}</code>.</p>
254 <p>Think of these class methods as executing in the context of their base
255 class, not in that of their derived class. Sometimes this is exactly
256 what you want. If Feline subclasses Carnivore, then the population of
257 Carnivores in the world should go up when a new Feline is born.
258 But what if you wanted to figure out how many Felines you have apart
259 from Carnivores? The current approach doesn't support that.</p>
260 <p>You'll have to decide on a case-by-case basis whether it makes any sense
261 for class attributes to be package-relative. If you want it to be so,
262 then stop ignoring the first argument to the function. Either it will
263 be a package name if the method was invoked directly on a class name,
264 or else it will be an object reference if the method was invoked on an
265 object reference. In the latter case, the <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_ref"><code>ref()</code></a> function provides the
266 class of that object.</p>
267 <pre>
268 package Some_Class;
269 sub CData1 {
270 my $obclass = shift;
271 my $class = ref($obclass) || $obclass;
272 my $varname = $class . &quot;::CData1&quot;;
273 no strict &quot;refs&quot;; # to access package data symbolically
274 $$varname = shift if @_;
275 return $$varname;
276 }</pre>
277 <p>And then do likewise for all other class attributes (such as CData2,
278 etc.) that you wish to access as package variables in the invoking package
279 instead of the compiling package as we had previously.</p>
280 <p>Once again we temporarily disable the strict references ban, because
281 otherwise we couldn't use the fully-qualified symbolic name for
282 the package global. This is perfectly reasonable: since all package
283 variables by definition live in a package, there's nothing wrong with
284 accessing them via that package's symbol table. That's what it's there
285 for (well, somewhat).</p>
286 <p>What about just using a single hash for everything and then cloning
287 methods? What would that look like? The only difference would be the
288 closure used to produce new method entries for the class's symbol table.</p>
289 <pre>
290 no strict &quot;refs&quot;;
291 *$datum = sub {
292 my $obclass = shift;
293 my $class = ref($obclass) || $obclass;
294 my $varname = $class . &quot;::ClassData&quot;;
295 $varname-&gt;{$datum} = shift if @_;
296 return $varname-&gt;{$datum};
297 }</pre>
299 </p>
300 <h2><a name="the_eponymous_metaobject">The Eponymous Meta-Object</a></h2>
301 <p>It could be argued that the %ClassData hash in the previous example is
302 neither the most imaginative nor the most intuitive of names. Is there
303 something else that might make more sense, be more useful, or both?</p>
304 <p>As it happens, yes, there is. For the ``class meta-object'', we'll use
305 a package variable of the same name as the package itself. Within the
306 scope of a package Some_Class declaration, we'll use the eponymously
307 named hash %Some_Class as that class's meta-object. (Using an eponymously
308 named hash is somewhat reminiscent of classes that name their constructors
309 eponymously in the Python or C++ fashion. That is, class Some_Class would
310 use &amp;Some_Class::Some_Class as a constructor, probably even exporting that
311 name as well. The StrNum class in Recipe 13.14 in <em>The Perl Cookbook</em>
312 does this, if you're looking for an example.)</p>
313 <p>This predictable approach has many benefits, including having a well-known
314 identifier to aid in debugging, transparent persistence,
315 or checkpointing. It's also the obvious name for monadic classes and
316 translucent attributes, discussed later.</p>
317 <p>Here's an example of such a class. Notice how the name of the
318 hash storing the meta-object is the same as the name of the package
319 used to implement the class.</p>
320 <pre>
321 package Some_Class;
322 use strict;</pre>
323 <pre>
324 # create class meta-object using that most perfect of names
325 our %Some_Class = ( # our() is new to perl5.6
326 CData1 =&gt; &quot;&quot;,
327 CData2 =&gt; &quot;&quot;,
328 );</pre>
329 <pre>
330 # this accessor is calling-package-relative
331 sub CData1 {
332 my $obclass = shift;
333 my $class = ref($obclass) || $obclass;
334 no strict &quot;refs&quot;; # to access eponymous meta-object
335 $class-&gt;{CData1} = shift if @_;
336 return $class-&gt;{CData1};
337 }</pre>
338 <pre>
339 # but this accessor is not
340 sub CData2 {
341 shift; # XXX: ignore calling class/object
342 no strict &quot;refs&quot;; # to access eponymous meta-object
343 __PACKAGE__ -&gt; {CData2} = shift if @_;
344 return __PACKAGE__ -&gt; {CData2};
345 }</pre>
346 <p>In the second accessor method, the __PACKAGE__ notation was used for
347 two reasons. First, to avoid hardcoding the literal package name
348 in the code in case we later want to change that name. Second, to
349 clarify to the reader that what matters here is the package currently
350 being compiled into, not the package of the invoking object or class.
351 If the long sequence of non-alphabetic characters bothers you, you can
352 always put the __PACKAGE__ in a variable first.</p>
353 <pre>
354 sub CData2 {
355 shift; # XXX: ignore calling class/object
356 no strict &quot;refs&quot;; # to access eponymous meta-object
357 my $class = __PACKAGE__;
358 $class-&gt;{CData2} = shift if @_;
359 return $class-&gt;{CData2};
360 }</pre>
361 <p>Even though we're using symbolic references for good not evil, some
362 folks tend to become unnerved when they see so many places with strict
363 ref checking disabled. Given a symbolic reference, you can always
364 produce a real reference (the reverse is not true, though). So we'll
365 create a subroutine that does this conversion for us. If invoked as a
366 function of no arguments, it returns a reference to the compiling class's
367 eponymous hash. Invoked as a class method, it returns a reference to
368 the eponymous hash of its caller. And when invoked as an object method,
369 this function returns a reference to the eponymous hash for whatever
370 class the object belongs to.</p>
371 <pre>
372 package Some_Class;
373 use strict;</pre>
374 <pre>
375 our %Some_Class = ( # our() is new to perl5.6
376 CData1 =&gt; &quot;&quot;,
377 CData2 =&gt; &quot;&quot;,
378 );</pre>
379 <pre>
380 # tri-natured: function, class method, or object method
381 sub _classobj {
382 my $obclass = shift || __PACKAGE__;
383 my $class = ref($obclass) || $obclass;
384 no strict &quot;refs&quot;; # to convert sym ref to real one
385 return \%$class;
386 }</pre>
387 <pre>
388 for my $datum (keys %{ _classobj() } ) {
389 # turn off strict refs so that we can
390 # register a method in the symbol table
391 no strict &quot;refs&quot;;
392 *$datum = sub {
393 use strict &quot;refs&quot;;
394 my $self = shift-&gt;_classobj();
395 $self-&gt;{$datum} = shift if @_;
396 return $self-&gt;{$datum};
398 }</pre>
400 </p>
401 <h2><a name="indirect_references_to_class_data">Indirect References to Class Data</a></h2>
402 <p>A reasonably common strategy for handling class attributes is to store
403 a reference to each package variable on the object itself. This is
404 a strategy you've probably seen before, such as in <a href="file://C|\msysgit\mingw\html/pod/perltoot.html">the perltoot manpage</a> and
405 <a href="file://C|\msysgit\mingw\html/pod/perlbot.html">the perlbot manpage</a>, but there may be variations in the example below that you
406 haven't thought of before.</p>
407 <pre>
408 package Some_Class;
409 our($CData1, $CData2); # our() is new to perl5.6</pre>
410 <pre>
411 sub new {
412 my $obclass = shift;
413 return bless my $self = {
414 ObData1 =&gt; &quot;&quot;,
415 ObData2 =&gt; &quot;&quot;,
416 CData1 =&gt; \$CData1,
417 CData2 =&gt; \$CData2,
418 } =&gt; (ref $obclass || $obclass);
419 }</pre>
420 <pre>
421 sub ObData1 {
422 my $self = shift;
423 $self-&gt;{ObData1} = shift if @_;
424 return $self-&gt;{ObData1};
425 }</pre>
426 <pre>
427 sub ObData2 {
428 my $self = shift;
429 $self-&gt;{ObData2} = shift if @_;
430 return $self-&gt;{ObData2};
431 }</pre>
432 <pre>
433 sub CData1 {
434 my $self = shift;
435 my $dataref = ref $self
436 ? $self-&gt;{CData1}
437 : \$CData1;
438 $$dataref = shift if @_;
439 return $$dataref;
440 }</pre>
441 <pre>
442 sub CData2 {
443 my $self = shift;
444 my $dataref = ref $self
445 ? $self-&gt;{CData2}
446 : \$CData2;
447 $$dataref = shift if @_;
448 return $$dataref;
449 }</pre>
450 <p>As written above, a derived class will inherit these methods, which
451 will consequently access package variables in the base class's package.
452 This is not necessarily expected behavior in all circumstances. Here's an
453 example that uses a variable meta-object, taking care to access the
454 proper package's data.</p>
455 <pre>
456 package Some_Class;
457 use strict;</pre>
458 <pre>
459 our %Some_Class = ( # our() is new to perl5.6
460 CData1 =&gt; &quot;&quot;,
461 CData2 =&gt; &quot;&quot;,
462 );</pre>
463 <pre>
464 sub _classobj {
465 my $self = shift;
466 my $class = ref($self) || $self;
467 no strict &quot;refs&quot;;
468 # get (hard) ref to eponymous meta-object
469 return \%$class;
470 }</pre>
471 <pre>
472 sub new {
473 my $obclass = shift;
474 my $classobj = $obclass-&gt;_classobj();
475 bless my $self = {
476 ObData1 =&gt; &quot;&quot;,
477 ObData2 =&gt; &quot;&quot;,
478 CData1 =&gt; \$classobj-&gt;{CData1},
479 CData2 =&gt; \$classobj-&gt;{CData2},
480 } =&gt; (ref $obclass || $obclass);
481 return $self;
482 }</pre>
483 <pre>
484 sub ObData1 {
485 my $self = shift;
486 $self-&gt;{ObData1} = shift if @_;
487 return $self-&gt;{ObData1};
488 }</pre>
489 <pre>
490 sub ObData2 {
491 my $self = shift;
492 $self-&gt;{ObData2} = shift if @_;
493 return $self-&gt;{ObData2};
494 }</pre>
495 <pre>
496 sub CData1 {
497 my $self = shift;
498 $self = $self-&gt;_classobj() unless ref $self;
499 my $dataref = $self-&gt;{CData1};
500 $$dataref = shift if @_;
501 return $$dataref;
502 }</pre>
503 <pre>
504 sub CData2 {
505 my $self = shift;
506 $self = $self-&gt;_classobj() unless ref $self;
507 my $dataref = $self-&gt;{CData2};
508 $$dataref = shift if @_;
509 return $$dataref;
510 }</pre>
511 <p>Not only are we now strict refs clean, using an eponymous meta-object
512 seems to make the code cleaner. Unlike the previous version, this one
513 does something interesting in the face of inheritance: it accesses the
514 class meta-object in the invoking class instead of the one into which
515 the method was initially compiled.</p>
516 <p>You can easily access data in the class meta-object, making
517 it easy to dump the complete class state using an external mechanism such
518 as when debugging or implementing a persistent class. This works because
519 the class meta-object is a package variable, has a well-known name, and
520 clusters all its data together. (Transparent persistence
521 is not always feasible, but it's certainly an appealing idea.)</p>
522 <p>There's still no check that object accessor methods have not been
523 invoked on a class name. If strict ref checking is enabled, you'd
524 blow up. If not, then you get the eponymous meta-object. What you do
525 with--or about--this is up to you. The next two sections demonstrate
526 innovative uses for this powerful feature.</p>
528 </p>
529 <h2><a name="monadic_classes">Monadic Classes</a></h2>
530 <p>Some of the standard modules shipped with Perl provide class interfaces
531 without any attribute methods whatsoever. The most commonly used module
532 not numbered amongst the pragmata, the Exporter module, is a class with
533 neither constructors nor attributes. Its job is simply to provide a
534 standard interface for modules wishing to export part of their namespace
535 into that of their caller. Modules use the Exporter's &amp;import method by
536 setting their inheritance list in their package's @ISA array to mention
537 ``Exporter''. But class Exporter provides no constructor, so you can't
538 have several instances of the class. In fact, you can't have any--it
539 just doesn't make any sense. All you get is its methods. Its interface
540 contains no statefulness, so state data is wholly superfluous.</p>
541 <p>Another sort of class that pops up from time to time is one that supports
542 a unique instance. Such classes are called <em>monadic classes</em>, or less
543 formally, <em>singletons</em> or <em>highlander classes</em>.</p>
544 <p>If a class is monadic, where do you store its state, that is,
545 its attributes? How do you make sure that there's never more than
546 one instance? While you could merely use a slew of package variables,
547 it's a lot cleaner to use the eponymously named hash. Here's a complete
548 example of a monadic class:</p>
549 <pre>
550 package Cosmos;
551 %Cosmos = ();</pre>
552 <pre>
553 # accessor method for &quot;name&quot; attribute
554 sub name {
555 my $self = shift;
556 $self-&gt;{name} = shift if @_;
557 return $self-&gt;{name};
558 }</pre>
559 <pre>
560 # read-only accessor method for &quot;birthday&quot; attribute
561 sub birthday {
562 my $self = shift;
563 die &quot;can't reset birthday&quot; if @_; # XXX: croak() is better
564 return $self-&gt;{birthday};
565 }</pre>
566 <pre>
567 # accessor method for &quot;stars&quot; attribute
568 sub stars {
569 my $self = shift;
570 $self-&gt;{stars} = shift if @_;
571 return $self-&gt;{stars};
572 }</pre>
573 <pre>
574 # oh my - one of our stars just went out!
575 sub supernova {
576 my $self = shift;
577 my $count = $self-&gt;stars();
578 $self-&gt;stars($count - 1) if $count &gt; 0;
579 }</pre>
580 <pre>
581 # constructor/initializer method - fix by reboot
582 sub bigbang {
583 my $self = shift;
584 %$self = (
585 name =&gt; &quot;the world according to tchrist&quot;,
586 birthday =&gt; time(),
587 stars =&gt; 0,
589 return $self; # yes, it's probably a class. SURPRISE!
590 }</pre>
591 <pre>
592 # After the class is compiled, but before any use or require
593 # returns, we start off the universe with a bang.
594 __PACKAGE__ -&gt; bigbang();</pre>
595 <p>Hold on, that doesn't look like anything special. Those attribute
596 accessors look no different than they would if this were a regular class
597 instead of a monadic one. The crux of the matter is there's nothing
598 that says that $self must hold a reference to a blessed object. It merely
599 has to be something you can invoke methods on. Here the package name
600 itself, Cosmos, works as an object. Look at the &amp;supernova method. Is that
601 a class method or an object method? The answer is that static analysis
602 cannot reveal the answer. Perl doesn't care, and neither should you.
603 In the three attribute methods, <code>%$self</code> is really accessing the %Cosmos
604 package variable.</p>
605 <p>If like Stephen Hawking, you posit the existence of multiple, sequential,
606 and unrelated universes, then you can invoke the &amp;bigbang method yourself
607 at any time to start everything all over again. You might think of
608 &amp;bigbang as more of an initializer than a constructor, since the function
609 doesn't allocate new memory; it only initializes what's already there.
610 But like any other constructor, it does return a scalar value to use
611 for later method invocations.</p>
612 <p>Imagine that some day in the future, you decide that one universe just
613 isn't enough. You could write a new class from scratch, but you already
614 have an existing class that does what you want--except that it's monadic,
615 and you want more than just one cosmos.</p>
616 <p>That's what code reuse via subclassing is all about. Look how short
617 the new code is:</p>
618 <pre>
619 package Multiverse;
620 use Cosmos;
621 @ISA = qw(Cosmos);</pre>
622 <pre>
623 sub new {
624 my $protoverse = shift;
625 my $class = ref($protoverse) || $protoverse;
626 my $self = {};
627 return bless($self, $class)-&gt;bigbang();
629 1;</pre>
630 <p>Because we were careful to be good little creators when we designed our
631 Cosmos class, we can now reuse it without touching a single line of code
632 when it comes time to write our Multiverse class. The same code that
633 worked when invoked as a class method continues to work perfectly well
634 when invoked against separate instances of a derived class.</p>
635 <p>The astonishing thing about the Cosmos class above is that the value
636 returned by the &amp;bigbang ``constructor'' is not a reference to a blessed
637 object at all. It's just the class's own name. A class name is, for
638 virtually all intents and purposes, a perfectly acceptable object.
639 It has state, behavior, and identity, the three crucial components
640 of an object system. It even manifests inheritance, polymorphism,
641 and encapsulation. And what more can you ask of an object?</p>
642 <p>To understand object orientation in Perl, it's important to recognize the
643 unification of what other programming languages might think of as class
644 methods and object methods into just plain methods. ``Class methods''
645 and ``object methods'' are distinct only in the compartmentalizing mind
646 of the Perl programmer, not in the Perl language itself.</p>
647 <p>Along those same lines, a constructor is nothing special either, which
648 is one reason why Perl has no pre-ordained name for them. ``Constructor''
649 is just an informal term loosely used to describe a method that returns
650 a scalar value that you can make further method calls against. So long
651 as it's either a class name or an object reference, that's good enough.
652 It doesn't even have to be a reference to a brand new object.</p>
653 <p>You can have as many--or as few--constructors as you want, and you can
654 name them whatever you care to. Blindly and obediently using <code>new()</code>
655 for each and every constructor you ever write is to speak Perl with
656 such a severe C++ accent that you do a disservice to both languages.
657 There's no reason to insist that each class have but one constructor,
658 or that a constructor be named new(), or that a constructor be
659 used solely as a class method and not an object method.</p>
660 <p>The next section shows how useful it can be to further distance ourselves
661 from any formal distinction between class method calls and object method
662 calls, both in constructors and in accessor methods.</p>
664 </p>
665 <h2><a name="translucent_attributes">Translucent Attributes</a></h2>
666 <p>A package's eponymous hash can be used for more than just containing
667 per-class, global state data. It can also serve as a sort of template
668 containing default settings for object attributes. These default
669 settings can then be used in constructors for initialization of a
670 particular object. The class's eponymous hash can also be used to
671 implement <em>translucent attributes</em>. A translucent attribute is one
672 that has a class-wide default. Each object can set its own value for the
673 attribute, in which case <code>$object-&gt;attribute()</code> returns that value.
674 But if no value has been set, then <code>$object-&gt;attribute()</code> returns
675 the class-wide default.</p>
676 <p>We'll apply something of a copy-on-write approach to these translucent
677 attributes. If you're just fetching values from them, you get
678 translucency. But if you store a new value to them, that new value is
679 set on the current object. On the other hand, if you use the class as
680 an object and store the attribute value directly on the class, then the
681 meta-object's value changes, and later fetch operations on objects with
682 uninitialized values for those attributes will retrieve the meta-object's
683 new values. Objects with their own initialized values, however, won't
684 see any change.</p>
685 <p>Let's look at some concrete examples of using these properties before we
686 show how to implement them. Suppose that a class named Some_Class
687 had a translucent data attribute called ``color''. First you set the color
688 in the meta-object, then you create three objects using a constructor
689 that happens to be named &amp;spawn.</p>
690 <pre>
691 use Vermin;
692 Vermin-&gt;color(&quot;vermilion&quot;);</pre>
693 <pre>
694 $ob1 = Vermin-&gt;spawn(); # so that's where Jedi come from
695 $ob2 = Vermin-&gt;spawn();
696 $ob3 = Vermin-&gt;spawn();</pre>
697 <pre>
698 print $obj3-&gt;color(); # prints &quot;vermilion&quot;</pre>
699 <p>Each of these objects' colors is now ``vermilion'', because that's the
700 meta-object's value for that attribute, and these objects do not have
701 individual color values set.</p>
702 <p>Changing the attribute on one object has no effect on other objects
703 previously created.</p>
704 <pre>
705 $ob3-&gt;color(&quot;chartreuse&quot;);
706 print $ob3-&gt;color(); # prints &quot;chartreuse&quot;
707 print $ob1-&gt;color(); # prints &quot;vermilion&quot;, translucently</pre>
708 <p>If you now use $ob3 to spawn off another object, the new object will
709 take the color its parent held, which now happens to be ``chartreuse''.
710 That's because the constructor uses the invoking object as its template
711 for initializing attributes. When that invoking object is the
712 class name, the object used as a template is the eponymous meta-object.
713 When the invoking object is a reference to an instantiated object, the
714 &amp;spawn constructor uses that existing object as a template.</p>
715 <pre>
716 $ob4 = $ob3-&gt;spawn(); # $ob3 now template, not %Vermin
717 print $ob4-&gt;color(); # prints &quot;chartreuse&quot;</pre>
718 <p>Any actual values set on the template object will be copied to the
719 new object. But attributes undefined in the template object, being
720 translucent, will remain undefined and consequently translucent in the
721 new one as well.</p>
722 <p>Now let's change the color attribute on the entire class:</p>
723 <pre>
724 Vermin-&gt;color(&quot;azure&quot;);
725 print $ob1-&gt;color(); # prints &quot;azure&quot;
726 print $ob2-&gt;color(); # prints &quot;azure&quot;
727 print $ob3-&gt;color(); # prints &quot;chartreuse&quot;
728 print $ob4-&gt;color(); # prints &quot;chartreuse&quot;</pre>
729 <p>That color change took effect only in the first pair of objects, which
730 were still translucently accessing the meta-object's values. The second
731 pair had per-object initialized colors, and so didn't change.</p>
732 <p>One important question remains. Changes to the meta-object are reflected
733 in translucent attributes in the entire class, but what about
734 changes to discrete objects? If you change the color of $ob3, does the
735 value of $ob4 see that change? Or vice-versa. If you change the color
736 of $ob4, does then the value of $ob3 shift?</p>
737 <pre>
738 $ob3-&gt;color(&quot;amethyst&quot;);
739 print $ob3-&gt;color(); # prints &quot;amethyst&quot;
740 print $ob4-&gt;color(); # hmm: &quot;chartreuse&quot; or &quot;amethyst&quot;?</pre>
741 <p>While one could argue that in certain rare cases it should, let's not
742 do that. Good taste aside, we want the answer to the question posed in
743 the comment above to be ``chartreuse'', not ``amethyst''. So we'll treat
744 these attributes similar to the way process attributes like environment
745 variables, user and group IDs, or the current working directory are
746 treated across a fork(). You can change only yourself, but you will see
747 those changes reflected in your unspawned children. Changes to one object
748 will propagate neither up to the parent nor down to any existing child objects.
749 Those objects made later, however, will see the changes.</p>
750 <p>If you have an object with an actual attribute value, and you want to
751 make that object's attribute value translucent again, what do you do?
752 Let's design the class so that when you invoke an accessor method with
753 <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_undef"><code>undef</code></a> as its argument, that attribute returns to translucency.</p>
754 <pre>
755 $ob4-&gt;color(undef); # back to &quot;azure&quot;</pre>
756 <p>Here's a complete implementation of Vermin as described above.</p>
757 <pre>
758 package Vermin;</pre>
759 <pre>
760 # here's the class meta-object, eponymously named.
761 # it holds all class attributes, and also all instance attributes
762 # so the latter can be used for both initialization
763 # and translucency.</pre>
764 <pre>
765 our %Vermin = ( # our() is new to perl5.6
766 PopCount =&gt; 0, # capital for class attributes
767 color =&gt; &quot;beige&quot;, # small for instance attributes
768 );</pre>
769 <pre>
770 # constructor method
771 # invoked as class method or object method
772 sub spawn {
773 my $obclass = shift;
774 my $class = ref($obclass) || $obclass;
775 my $self = {};
776 bless($self, $class);
777 $class-&gt;{PopCount}++;
778 # init fields from invoking object, or omit if
779 # invoking object is the class to provide translucency
780 %$self = %$obclass if ref $obclass;
781 return $self;
782 }</pre>
783 <pre>
784 # translucent accessor for &quot;color&quot; attribute
785 # invoked as class method or object method
786 sub color {
787 my $self = shift;
788 my $class = ref($self) || $self;</pre>
789 <pre>
790 # handle class invocation
791 unless (ref $self) {
792 $class-&gt;{color} = shift if @_;
793 return $class-&gt;{color}
794 }</pre>
795 <pre>
796 # handle object invocation
797 $self-&gt;{color} = shift if @_;
798 if (defined $self-&gt;{color}) { # not exists!
799 return $self-&gt;{color};
800 } else {
801 return $class-&gt;{color};
803 }</pre>
804 <pre>
805 # accessor for &quot;PopCount&quot; class attribute
806 # invoked as class method or object method
807 # but uses object solely to locate meta-object
808 sub population {
809 my $obclass = shift;
810 my $class = ref($obclass) || $obclass;
811 return $class-&gt;{PopCount};
812 }</pre>
813 <pre>
814 # instance destructor
815 # invoked only as object method
816 sub DESTROY {
817 my $self = shift;
818 my $class = ref $self;
819 $class-&gt;{PopCount}--;
820 }</pre>
821 <p>Here are a couple of helper methods that might be convenient. They aren't
822 accessor methods at all. They're used to detect accessibility of data
823 attributes. The &amp;is_translucent method determines whether a particular
824 object attribute is coming from the meta-object. The &amp;has_attribute
825 method detects whether a class implements a particular property at all.
826 It could also be used to distinguish undefined properties from non-existent
827 ones.</p>
828 <pre>
829 # detect whether an object attribute is translucent
830 # (typically?) invoked only as object method
831 sub is_translucent {
832 my($self, $attr) = @_;
833 return !defined $self-&gt;{$attr};
834 }</pre>
835 <pre>
836 # test for presence of attribute in class
837 # invoked as class method or object method
838 sub has_attribute {
839 my($self, $attr) = @_;
840 my $class = ref($self) || $self;
841 return exists $class-&gt;{$attr};
842 }</pre>
843 <p>If you prefer to install your accessors more generically, you can make
844 use of the upper-case versus lower-case convention to register into the
845 package appropriate methods cloned from generic closures.</p>
846 <pre>
847 for my $datum (keys %{ +__PACKAGE__ }) {
848 *$datum = ($datum =~ /^[A-Z]/)
849 ? sub { # install class accessor
850 my $obclass = shift;
851 my $class = ref($obclass) || $obclass;
852 return $class-&gt;{$datum};
854 : sub { # install translucent accessor
855 my $self = shift;
856 my $class = ref($self) || $self;
857 unless (ref $self) {
858 $class-&gt;{$datum} = shift if @_;
859 return $class-&gt;{$datum}
861 $self-&gt;{$datum} = shift if @_;
862 return defined $self-&gt;{$datum}
863 ? $self -&gt; {$datum}
864 : $class -&gt; {$datum}
866 }</pre>
867 <p>Translations of this closure-based approach into C++, Java, and Python
868 have been left as exercises for the reader. Be sure to send us mail as
869 soon as you're done.</p>
871 </p>
872 <hr />
873 <h1><a name="class_data_as_lexical_variables">Class Data as Lexical Variables</a></h1>
875 </p>
876 <h2><a name="privacy_and_responsibility">Privacy and Responsibility</a></h2>
877 <p>Unlike conventions used by some Perl programmers, in the previous
878 examples, we didn't prefix the package variables used for class attributes
879 with an underscore, nor did we do so for the names of the hash keys used
880 for instance attributes. You don't need little markers on data names to
881 suggest nominal privacy on attribute variables or hash keys, because these
882 are <strong>already</strong> notionally private! Outsiders have no business whatsoever
883 playing with anything within a class save through the mediated access of
884 its documented interface; in other words, through method invocations.
885 And not even through just any method, either. Methods that begin with
886 an underscore are traditionally considered off-limits outside the class.
887 If outsiders skip the documented method interface to poke around the
888 internals of your class and end up breaking something, that's not your
889 fault--it's theirs.</p>
890 <p>Perl believes in individual responsibility rather than mandated control.
891 Perl respects you enough to let you choose your own preferred level of
892 pain, or of pleasure. Perl believes that you are creative, intelligent,
893 and capable of making your own decisions--and fully expects you to
894 take complete responsibility for your own actions. In a perfect world,
895 these admonitions alone would suffice, and everyone would be intelligent,
896 responsible, happy, and creative. And careful. One probably shouldn't
897 forget careful, and that's a good bit harder to expect. Even Einstein
898 would take wrong turns by accident and end up lost in the wrong part
899 of town.</p>
900 <p>Some folks get the heebie-jeebies when they see package variables
901 hanging out there for anyone to reach over and alter them. Some folks
902 live in constant fear that someone somewhere might do something wicked.
903 The solution to that problem is simply to fire the wicked, of course.
904 But unfortunately, it's not as simple as all that. These cautious
905 types are also afraid that they or others will do something not so
906 much wicked as careless, whether by accident or out of desperation.
907 If we fire everyone who ever gets careless, pretty soon there won't be
908 anybody left to get any work done.</p>
909 <p>Whether it's needless paranoia or sensible caution, this uneasiness can
910 be a problem for some people. We can take the edge off their discomfort
911 by providing the option of storing class attributes as lexical variables
912 instead of as package variables. The <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_my"><code>my()</code></a> operator is the source of
913 all privacy in Perl, and it is a powerful form of privacy indeed.</p>
914 <p>It is widely perceived, and indeed has often been written, that Perl
915 provides no data hiding, that it affords the class designer no privacy
916 nor isolation, merely a rag-tag assortment of weak and unenforceable
917 social conventions instead. This perception is demonstrably false and
918 easily disproven. In the next section, we show how to implement forms
919 of privacy that are far stronger than those provided in nearly any
920 other object-oriented language.</p>
922 </p>
923 <h2><a name="filescoped_lexicals">File-Scoped Lexicals</a></h2>
924 <p>A lexical variable is visible only through the end of its static scope.
925 That means that the only code able to access that variable is code
926 residing textually below the <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_my"><code>my()</code></a> operator through the end of its block
927 if it has one, or through the end of the current file if it doesn't.</p>
928 <p>Starting again with our simplest example given at the start of this
929 document, we replace <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_our"><code>our()</code></a> variables with <a href="file://C|\msysgit\mingw\html/pod/perlfunc.html#item_my"><code>my()</code></a> versions.</p>
930 <pre>
931 package Some_Class;
932 my($CData1, $CData2); # file scope, not in any package
933 sub CData1 {
934 shift; # XXX: ignore calling class/object
935 $CData1 = shift if @_;
936 return $CData1;
938 sub CData2 {
939 shift; # XXX: ignore calling class/object
940 $CData2 = shift if @_;
941 return $CData2;
942 }</pre>
943 <p>So much for that old $Some_Class::CData1 package variable and its brethren!
944 Those are gone now, replaced with lexicals. No one outside the
945 scope can reach in and alter the class state without resorting to the
946 documented interface. Not even subclasses or superclasses of
947 this one have unmediated access to $CData1. They have to invoke the &amp;CData1
948 method against Some_Class or an instance thereof, just like anybody else.</p>
949 <p>To be scrupulously honest, that last statement assumes you haven't packed
950 several classes together into the same file scope, nor strewn your class
951 implementation across several different files. Accessibility of those
952 variables is based uniquely on the static file scope. It has nothing to
953 do with the package. That means that code in a different file but
954 the same package (class) could not access those variables, yet code in the
955 same file but a different package (class) could. There are sound reasons
956 why we usually suggest a one-to-one mapping between files and packages
957 and modules and classes. You don't have to stick to this suggestion if
958 you really know what you're doing, but you're apt to confuse yourself
959 otherwise, especially at first.</p>
960 <p>If you'd like to aggregate your class attributes into one lexically scoped,
961 composite structure, you're perfectly free to do so.</p>
962 <pre>
963 package Some_Class;
964 my %ClassData = (
965 CData1 =&gt; &quot;&quot;,
966 CData2 =&gt; &quot;&quot;,
968 sub CData1 {
969 shift; # XXX: ignore calling class/object
970 $ClassData{CData1} = shift if @_;
971 return $ClassData{CData1};
973 sub CData2 {
974 shift; # XXX: ignore calling class/object
975 $ClassData{CData2} = shift if @_;
976 return $ClassData{CData2};
977 }</pre>
978 <p>To make this more scalable as other class attributes are added, we can
979 again register closures into the package symbol table to create accessor
980 methods for them.</p>
981 <pre>
982 package Some_Class;
983 my %ClassData = (
984 CData1 =&gt; &quot;&quot;,
985 CData2 =&gt; &quot;&quot;,
987 for my $datum (keys %ClassData) {
988 no strict &quot;refs&quot;;
989 *$datum = sub {
990 shift; # XXX: ignore calling class/object
991 $ClassData{$datum} = shift if @_;
992 return $ClassData{$datum};
994 }</pre>
995 <p>Requiring even your own class to use accessor methods like anybody else is
996 probably a good thing. But demanding and expecting that everyone else,
997 be they subclass or superclass, friend or foe, will all come to your
998 object through mediation is more than just a good idea. It's absolutely
999 critical to the model. Let there be in your mind no such thing as
1000 ``public'' data, nor even ``protected'' data, which is a seductive but
1001 ultimately destructive notion. Both will come back to bite at you.
1002 That's because as soon as you take that first step out of the solid
1003 position in which all state is considered completely private, save from the
1004 perspective of its own accessor methods, you have violated the envelope.
1005 And, having pierced that encapsulating envelope, you shall doubtless
1006 someday pay the price when future changes in the implementation break
1007 unrelated code. Considering that avoiding this infelicitous outcome was
1008 precisely why you consented to suffer the slings and arrows of obsequious
1009 abstraction by turning to object orientation in the first place, such
1010 breakage seems unfortunate in the extreme.</p>
1012 </p>
1013 <h2><a name="more_inheritance_concerns">More Inheritance Concerns</a></h2>
1014 <p>Suppose that Some_Class were used as a base class from which to derive
1015 Another_Class. If you invoke a &amp;CData method on the derived class or
1016 on an object of that class, what do you get? Would the derived class
1017 have its own state, or would it piggyback on its base class's versions
1018 of the class attributes?</p>
1019 <p>The answer is that under the scheme outlined above, the derived class
1020 would <strong>not</strong> have its own state data. As before, whether you consider
1021 this a good thing or a bad one depends on the semantics of the classes
1022 involved.</p>
1023 <p>The cleanest, sanest, simplest way to address per-class state in a
1024 lexical is for the derived class to override its base class's version
1025 of the method that accesses the class attributes. Since the actual method
1026 called is the one in the object's derived class if this exists, you
1027 automatically get per-class state this way. Any urge to provide an
1028 unadvertised method to sneak out a reference to the %ClassData hash
1029 should be strenuously resisted.</p>
1030 <p>As with any other overridden method, the implementation in the
1031 derived class always has the option of invoking its base class's
1032 version of the method in addition to its own. Here's an example:</p>
1033 <pre>
1034 package Another_Class;
1035 @ISA = qw(Some_Class);</pre>
1036 <pre>
1037 my %ClassData = (
1038 CData1 =&gt; &quot;&quot;,
1039 );</pre>
1040 <pre>
1041 sub CData1 {
1042 my($self, $newvalue) = @_;
1043 if (@_ &gt; 1) {
1044 # set locally first
1045 $ClassData{CData1} = $newvalue;</pre>
1046 <pre>
1047 # then pass the buck up to the first
1048 # overridden version, if there is one
1049 if ($self-&gt;can(&quot;SUPER::CData1&quot;)) {
1050 $self-&gt;SUPER::CData1($newvalue);
1053 return $ClassData{CData1};
1054 }</pre>
1055 <p>Those dabbling in multiple inheritance might be concerned
1056 about there being more than one override.</p>
1057 <pre>
1058 for my $parent (@ISA) {
1059 my $methname = $parent . &quot;::CData1&quot;;
1060 if ($self-&gt;can($methname)) {
1061 $self-&gt;$methname($newvalue);
1063 }</pre>
1064 <p>Because the &amp;UNIVERSAL::can method returns a reference
1065 to the function directly, you can use this directly
1066 for a significant performance improvement:</p>
1067 <pre>
1068 for my $parent (@ISA) {
1069 if (my $coderef = $self-&gt;can($parent . &quot;::CData1&quot;)) {
1070 $self-&gt;$coderef($newvalue);
1072 }</pre>
1073 <p>If you override <code>UNIVERSAL::can</code> in your own classes, be sure to return the
1074 reference appropriately.</p>
1076 </p>
1077 <h2><a name="locking_the_door_and_throwing_away_the_key">Locking the Door and Throwing Away the Key</a></h2>
1078 <p>As currently implemented, any code within the same scope as the
1079 file-scoped lexical %ClassData can alter that hash directly. Is that
1080 ok? Is it acceptable or even desirable to allow other parts of the
1081 implementation of this class to access class attributes directly?</p>
1082 <p>That depends on how careful you want to be. Think back to the Cosmos
1083 class. If the &amp;supernova method had directly altered $Cosmos::Stars or
1084 <code>$Cosmos::Cosmos{stars}</code>, then we wouldn't have been able to reuse the
1085 class when it came to inventing a Multiverse. So letting even the class
1086 itself access its own class attributes without the mediating intervention of
1087 properly designed accessor methods is probably not a good idea after all.</p>
1088 <p>Restricting access to class attributes from the class itself is usually
1089 not enforceable even in strongly object-oriented languages. But in Perl,
1090 you can.</p>
1091 <p>Here's one way:</p>
1092 <pre>
1093 package Some_Class;</pre>
1094 <pre>
1095 { # scope for hiding $CData1
1096 my $CData1;
1097 sub CData1 {
1098 shift; # XXX: unused
1099 $CData1 = shift if @_;
1100 return $CData1;
1102 }</pre>
1103 <pre>
1104 { # scope for hiding $CData2
1105 my $CData2;
1106 sub CData2 {
1107 shift; # XXX: unused
1108 $CData2 = shift if @_;
1109 return $CData2;
1111 }</pre>
1112 <p>No one--absolutely no one--is allowed to read or write the class
1113 attributes without the mediation of the managing accessor method, since
1114 only that method has access to the lexical variable it's managing.
1115 This use of mediated access to class attributes is a form of privacy far
1116 stronger than most OO languages provide.</p>
1117 <p>The repetition of code used to create per-datum accessor methods chafes
1118 at our Laziness, so we'll again use closures to create similar
1119 methods.</p>
1120 <pre>
1121 package Some_Class;</pre>
1122 <pre>
1123 { # scope for ultra-private meta-object for class attributes
1124 my %ClassData = (
1125 CData1 =&gt; &quot;&quot;,
1126 CData2 =&gt; &quot;&quot;,
1127 );</pre>
1128 <pre>
1129 for my $datum (keys %ClassData ) {
1130 no strict &quot;refs&quot;;
1131 *$datum = sub {
1132 use strict &quot;refs&quot;;
1133 my ($self, $newvalue) = @_;
1134 $ClassData{$datum} = $newvalue if @_ &gt; 1;
1135 return $ClassData{$datum};
1137 }</pre>
1138 <pre>
1139 }</pre>
1140 <p>The closure above can be modified to take inheritance into account using
1141 the &amp;UNIVERSAL::can method and SUPER as shown previously.</p>
1143 </p>
1144 <h2><a name="translucency_revisited">Translucency Revisited</a></h2>
1145 <p>The Vermin class demonstrates translucency using a package variable,
1146 eponymously named %Vermin, as its meta-object. If you prefer to
1147 use absolutely no package variables beyond those necessary to appease
1148 inheritance or possibly the Exporter, this strategy is closed to you.
1149 That's too bad, because translucent attributes are an appealing
1150 technique, so it would be valuable to devise an implementation using
1151 only lexicals.</p>
1152 <p>There's a second reason why you might wish to avoid the eponymous
1153 package hash. If you use class names with double-colons in them, you
1154 would end up poking around somewhere you might not have meant to poke.</p>
1155 <pre>
1156 package Vermin;
1157 $class = &quot;Vermin&quot;;
1158 $class-&gt;{PopCount}++;
1159 # accesses $Vermin::Vermin{PopCount}</pre>
1160 <pre>
1161 package Vermin::Noxious;
1162 $class = &quot;Vermin::Noxious&quot;;
1163 $class-&gt;{PopCount}++;
1164 # accesses $Vermin::Noxious{PopCount}</pre>
1165 <p>In the first case, because the class name had no double-colons, we got
1166 the hash in the current package. But in the second case, instead of
1167 getting some hash in the current package, we got the hash %Noxious in
1168 the Vermin package. (The noxious vermin just invaded another package and
1169 sprayed their data around it. :-) Perl doesn't support relative packages
1170 in its naming conventions, so any double-colons trigger a fully-qualified
1171 lookup instead of just looking in the current package.</p>
1172 <p>In practice, it is unlikely that the Vermin class had an existing
1173 package variable named %Noxious that you just blew away. If you're
1174 still mistrustful, you could always stake out your own territory
1175 where you know the rules, such as using Eponymous::Vermin::Noxious or
1176 Hieronymus::Vermin::Boschious or Leave_Me_Alone::Vermin::Noxious as class
1177 names instead. Sure, it's in theory possible that someone else has
1178 a class named Eponymous::Vermin with its own %Noxious hash, but this
1179 kind of thing is always true. There's no arbiter of package names.
1180 It's always the case that globals like @Cwd::ISA would collide if more
1181 than one class uses the same Cwd package.</p>
1182 <p>If this still leaves you with an uncomfortable twinge of paranoia,
1183 we have another solution for you. There's nothing that says that you
1184 have to have a package variable to hold a class meta-object, either for
1185 monadic classes or for translucent attributes. Just code up the methods
1186 so that they access a lexical instead.</p>
1187 <p>Here's another implementation of the Vermin class with semantics identical
1188 to those given previously, but this time using no package variables.</p>
1189 <pre>
1190 package Vermin;</pre>
1191 <pre>
1192 # Here's the class meta-object, eponymously named.
1193 # It holds all class data, and also all instance data
1194 # so the latter can be used for both initialization
1195 # and translucency. it's a template.
1196 my %ClassData = (
1197 PopCount =&gt; 0, # capital for class attributes
1198 color =&gt; &quot;beige&quot;, # small for instance attributes
1199 );</pre>
1200 <pre>
1201 # constructor method
1202 # invoked as class method or object method
1203 sub spawn {
1204 my $obclass = shift;
1205 my $class = ref($obclass) || $obclass;
1206 my $self = {};
1207 bless($self, $class);
1208 $ClassData{PopCount}++;
1209 # init fields from invoking object, or omit if
1210 # invoking object is the class to provide translucency
1211 %$self = %$obclass if ref $obclass;
1212 return $self;
1213 }</pre>
1214 <pre>
1215 # translucent accessor for &quot;color&quot; attribute
1216 # invoked as class method or object method
1217 sub color {
1218 my $self = shift;</pre>
1219 <pre>
1220 # handle class invocation
1221 unless (ref $self) {
1222 $ClassData{color} = shift if @_;
1223 return $ClassData{color}
1224 }</pre>
1225 <pre>
1226 # handle object invocation
1227 $self-&gt;{color} = shift if @_;
1228 if (defined $self-&gt;{color}) { # not exists!
1229 return $self-&gt;{color};
1230 } else {
1231 return $ClassData{color};
1233 }</pre>
1234 <pre>
1235 # class attribute accessor for &quot;PopCount&quot; attribute
1236 # invoked as class method or object method
1237 sub population {
1238 return $ClassData{PopCount};
1239 }</pre>
1240 <pre>
1241 # instance destructor; invoked only as object method
1242 sub DESTROY {
1243 $ClassData{PopCount}--;
1244 }</pre>
1245 <pre>
1246 # detect whether an object attribute is translucent
1247 # (typically?) invoked only as object method
1248 sub is_translucent {
1249 my($self, $attr) = @_;
1250 $self = \%ClassData if !ref $self;
1251 return !defined $self-&gt;{$attr};
1252 }</pre>
1253 <pre>
1254 # test for presence of attribute in class
1255 # invoked as class method or object method
1256 sub has_attribute {
1257 my($self, $attr) = @_;
1258 return exists $ClassData{$attr};
1259 }</pre>
1261 </p>
1262 <hr />
1263 <h1><a name="notes">NOTES</a></h1>
1264 <p>Inheritance is a powerful but subtle device, best used only after careful
1265 forethought and design. Aggregation instead of inheritance is often a
1266 better approach.</p>
1267 <p>You can't use file-scoped lexicals in conjunction with the SelfLoader
1268 or the AutoLoader, because they alter the lexical scope in which the
1269 module's methods wind up getting compiled.</p>
1270 <p>The usual mealy-mouthed package-munging doubtless applies to setting
1271 up names of object attributes. For example, <code>$self-&gt;{ObData1}</code>
1272 should probably be <code>$self-&gt;{ __PACKAGE__ . &quot;_ObData1&quot; }</code>, but that
1273 would just confuse the examples.</p>
1275 </p>
1276 <hr />
1277 <h1><a name="see_also">SEE ALSO</a></h1>
1278 <p><a href="file://C|\msysgit\mingw\html/pod/perltoot.html">the perltoot manpage</a>, <a href="file://C|\msysgit\mingw\html/pod/perlobj.html">the perlobj manpage</a>, <a href="file://C|\msysgit\mingw\html/pod/perlmod.html">the perlmod manpage</a>, and <a href="file://C|\msysgit\mingw\html/pod/perlbot.html">the perlbot manpage</a>.</p>
1279 <p>The Tie::SecureHash and Class::Data::Inheritable modules from CPAN are
1280 worth checking out.</p>
1282 </p>
1283 <hr />
1284 <h1><a name="author_and_copyright">AUTHOR AND COPYRIGHT</a></h1>
1285 <p>Copyright (c) 1999 Tom Christiansen.
1286 All rights reserved.</p>
1287 <p>This documentation is free; you can redistribute it and/or modify it
1288 under the same terms as Perl itself.</p>
1289 <p>Irrespective of its distribution, all code examples in this file
1290 are hereby placed into the public domain. You are permitted and
1291 encouraged to use this code in your own programs for fun
1292 or for profit as you see fit. A simple comment in the code giving
1293 credit would be courteous but is not required.</p>
1295 </p>
1296 <hr />
1297 <h1><a name="acknowledgements">ACKNOWLEDGEMENTS</a></h1>
1298 <p>Russ Allbery, Jon Orwant, Randy Ray, Larry Rosler, Nat Torkington,
1299 and Stephen Warren all contributed suggestions and corrections to this
1300 piece. Thanks especially to Damian Conway for his ideas and feedback,
1301 and without whose indirect prodding I might never have taken the time
1302 to show others how much Perl has to offer in the way of objects once
1303 you start thinking outside the tiny little box that today's ``popular''
1304 object-oriented languages enforce.</p>
1306 </p>
1307 <hr />
1308 <h1><a name="history">HISTORY</a></h1>
1309 <p>Last edit: Sun Feb 4 20:50:28 EST 2001</p>
1310 <table border="0" width="100%" cellspacing="0" cellpadding="3">
1311 <tr><td class="block" style="background-color: #cccccc" valign="middle">
1312 <big><strong><span class="block">&nbsp;perltooc - Tom's OO Tutorial for Class Data in Perl</span></strong></big>
1313 </td></tr>
1314 </table>
1316 </body>
1318 </html>