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