1<!-- Copyright (c) 2001 by Jean-Luc Fontaine <jfontain@free.fr> -->
2<!--$Id: stooop_man.html,v 1.3 2004/01/15 06:36:14 andreas_kupries Exp $-->
3<html lang="en">
4<head>
5   <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
6   <title>stooop (Simple Tcl Only Object Oriented Programming)</title>
7</head>
8<body>
9
10<center><h1>stooop</h1></center>
11
12<center><h2>(Simple Tcl Only Object Oriented Programming)</h2></center>
13
14Stooop is an extension to the great Tcl language written in Tcl itself. The object oriented features of stooop are modeled after the C++ programming language while following the Tcl language philosophy.
15
16<h3>Contents</h3>
17
18<ul>
19  <li><a href="#about">About this document</a>
20  <li><a href="#introduction">Introduction</a>
21  <li><a href="#simple">Simple example</a>
22  <li><a href="#conventions">Coding conventions</a><ul>
23    <li><a href="#definition">Class definition</a>
24    <li><a href="#procedures">Member procedures</a><ul>
25      <li><a href="#constructor">Constructor</a>
26      <li><a href="#destructor">Destructor</a>
27      <li><a href="#proceduresnonstatic">Non static</a>
28      <li><a href="#proceduresstatic">Static</a>
29      <li><a href="#copy">Copy constructor</a>
30    </ul>
31    <li><a href="#data">Member data</a><ul>
32      <li><a href="#datanonstatic">Non static</a>
33      <li><a href="#datastatic">Static</a>
34    </ul>
35  </ul>
36  <li><a href="#keywords">Commands</a><ul>
37    <li><a href="#class">class</a>
38    <li><a href="#new">new</a>
39    <li><a href="#delete">delete</a>
40    <li><a href="#virtual">virtual</a>
41    <li><a href="#classof">classof</a>
42  </ul>
43  <li><a href="#package">Package</a><ul>
44    <li><a href="#installation">Installation</a>
45    <li><a href="#creation">Creation</a>
46  </ul>
47  <li><a href="#examples">Examples</a><ul>
48    <li><a href="#parallel">Parallel with C++</a>
49    <li><a href="#graphical">Graphical demonstration</a>
50    <li><a href="#widget">Widget class</a>
51    <li><a href="#array">Member array</a>
52  </ul>
53  <li><a href="#utility">Utility classes</a><ul>
54    <li><a href="#switched">switched</a>
55  </ul>
56  <li><a href="#debugging">Debugging</a><ul>
57    <li><a href="#check">member check</a><ul>
58      <li><a href="#procedurecheck">procedure</a>
59      <li><a href="#datacheck">data</a>
60    </ul>
61    <li><a href="#trace">member trace</a><ul>
62      <li><a href="#proceduretrace">procedure</a>
63      <li><a href="#datatrace">data</a>
64    </ul>
65    <li><a href="#objects">objects</a><ul>
66      <li><a href="#objects.printing">printing</a>
67      <li><a href="#objects.recording">recording</a>
68      <li><a href="#objects.reporting">reporting</a>
69    </ul>
70  </ul>
71  <li><a href="#notes">Notes</a><ul>
72    <li><a href="#design">On design choices</a>
73    <li><a href="#implementation">On implementation</a>
74  </ul>
75  <li><a href="#misc">Miscellaneous information</a>
76</ul>
77
78<h3><a name="about"></a>About this document</h3>
79
80This document contains general information, reference information and many examples designed to help the programmer understand and use the stooop extension (version 4.1.1 and above).
81
82<p>A working knowledge of object oriented programming techniques and a related programming language (C++, Java, ...) significantly helps understand this document.
83
84<h3><a name="introduction"></a>Introduction</h3>
85
86After some time writing Tcl/Tk code, I felt that I needed a way to improve the structure of my code, and why not use an object oriented approach, since I knew (but does anybody really? :-) C++. As I have used Tcl quite extensively in several commercial applications running on different operating systems and hardware, I decided to use a strict Tcl implementation for my object oriented extension. Consequently, stooop is compatible with all the Tcl ports (UNIX, Windows, MacIntosh).
87
88<p>Great care was taken so that this extension would no adverse impact on performance. Furthermore, designing your code in an object oriented should improve its performance, by focusing on well written pieces of reusable code.
89
90<p>Stooop only introduces a few new commands: <a href="#class">class</a>, <a href="#new">new</a>, <a href="#delete">delete</a>, <a href="#virtual">virtual</a> and <a href="#classof">classof</a>. Along with a few coding conventions, that is basically all you need to know to use stooop. Stooop is meant to be as simple to use as possible.
91
92<p>Starting with stooop version 3.2, nested classes are supported (see <a href="#class">class</a>), whereas version 3.3 and above support procedure and data members checking as well as tracing (see <a href="#debugging">debugging</a>).
93
94<p>Tcl version 8.2 and above supports the empty name array syntax, as in:
95
96<pre>set (m) 0 ;# set member m of array {} to 0
97set n $(m) ;# which actually sets n to 0</pre>
98
99This feature greatly simplifies class member manipulation in stooop classes and significantly improves performance. Stooop version 4.0 and above also uses this feature internally for further improvements, without sacrificing backward compatibility: code written against stooop versions 3.7 and below still works with stooop version 4.0 and above, but can be gradually moved to the simpler syntax when convenient.<br>
100Stooop 4.1 and above will only work out of the box with Tcl 8.3 and above.
101
102<h3><a name="simple"></a>Simple example</h3>
103
104Let us start with a code sample that will give you some feeling on how stooop works:
105
106<pre>package require stooop 4                                  ;# load stooop package
107namespace import stooop::*                ;# and import class, new, ... commands</pre>
108
109<pre>class shape {                                           ;# base class definition
110    proc shape {this x y} {                            ;# base class constructor
111        set ($this,x) $x                           ;# data member initialization
112        set ($this,y) $y
113    }
114    proc ~shape {this} {}                               ;# base class destructor
115    # pure virtual draw: must be implemented in derived classes
116    virtual proc draw {this}
117    virtual proc rotate {this angle} {}                 ;# do nothing by default
118}
119proc shape::move {this x y} {            ;# external member procedure definition
120    set ($this,x) $x
121    set ($this,y) $y
122    draw $this               ;# shape::draw invokes derived class implementation
123}
124
125class triangle {                                             ;# class definition
126    proc triangle {this x y} shape {$x $y} {               ;# derived from shape
127        # triangle constructor implementation
128    }
129    proc ~triangle {this} {}
130    proc draw {this} {
131        # triangle specific implementation
132    }
133    proc rotate {this angle} {
134        # triangle specific implementation
135    }
136}
137
138class circle {}        ;# empty class definition, procedures are defined outside
139proc circle::circle {this x y} shape {$x $y} {             ;# derived from shape
140    # circle constructor implementation
141}
142proc circle::~circle {this} {}
143proc circle::draw {this} {
144    # circle specific implementation
145}
146# circle::rotate procedure is a noop, no need to overload
147
148lappend shapes [new circle 20 20] [new triangle 80 20]
149foreach object $shapes {
150    shape::draw $object
151    shape::rotate $object 45
152}
153eval delete $shapes</pre>
154
155<h3><a name="conventions"></a>Coding conventions</h3>
156
157I have tried to make stooop Tcl code look like C++ code. There are exceptions of course.
158
159<h4><a name="definition"></a>Class definition</h4>
160
161The syntax is very simple:
162
163<pre>class className { ...</pre>
164
165<p>The member procedures are then defined, inside or outside the class definition (see below). Note that the base classes if any are defined within the constructor declaration where they are required for eventually passing constructor parameters, not in the actual class declaration where they would then be redundant.
166
167<p>As a class is a namespace, it is just as easy to nest classes as it is namespaces.
168
169<h4><a name="procedures"></a>Member procedures</h4>
170
171They can be defined inside or outside their class definition. When defined inside the class definition, the class name qualifier (<i>shape::</i> for example) before the procedure name must be omitted (a class is a Tcl namespace). When defined outside the class definition, the class name qualifier must be present (same reason). You may notice that the class definition and the related member procedures look very much like the Tcl <i>namespace</i> feature: it is because classes are indeed namespaces with a few more features added to support object orientation.
172
173<p>Member procedures are named as in C++ (for example, the <i>rotate</i> procedure of the class <i>shape</i> is referred to as <i>shape::rotate</i> in the global namespace). They are defined using the Tcl <i>proc</i> command, which is redefined by stooop in order to do some specific additional processing. Of course, global level and other namespaces procedures are not affected by stooop.
174
175<h5><a name="constructor"></a>Constructor</h5>
176
177A constructor is used to initialize an object of its class. The constructor is invoked by the <a href="#new">new</a> operator when an object of the class is created (instanciated in OO terms). The constructor is named as in C++ (for example, the <i>shape</i> constructor fully qualified name is <i>shape::shape</i>).
178
179<p>The constructor always takes the object identifier (a unique value generated by the command new) as the first parameter, plus eventually additional parameters as in the normal Tcl proc command. Arguments with default values are allowed, and so are variable number of arguments (see below). In all cases, the first parameter must be named <b>this</b>.
180
181<p><i><b>Note</b>: the object identifier is a unique integer value which is internally incremented by stooop each time a new object is created. Consequently, the greater the object identifier, the younger the object.</i>
182
183<p>Sample code of a constructor of a simple class with no base class:
184
185<pre>class shape {
186    proc shape {this x y} {
187        # implementation here
188    }
189}</pre>
190
191If a class is derived from one or more base classes, the derived class constructor defines the base classes and their constructor arguments before the actual body of the constructor.
192
193<p><i><b>Note</b>: base classes are not defined at the class command level, because it would be redundant with the constructor definition, which is mandatory.</i>
194
195<p>The derived class constructor parameters are followed by "base class names / constructor arguments" pairs. For each base class, there must be a corresponding list of constructor arguments to be used when the object is constructed when the new operator is invoked with the derived class name as argument.
196
197<p>Sample code for a class constructor with a single base class:
198
199<pre>class circle {}
200proc circle::circle {this x y} shape {$x $y} {
201    # circle constructor implementation
202}</pre>
203
204Sample code for a class constructor with multiple base classes:
205
206<pre>class hydroplane {
207    proc hydroplane {this wingspan length} plane {
208        $wingspan $length
209    } boat {
210        $length
211    {
212        # constructor implementation
213    }
214}</pre>
215
216The base class constructor arguments must be prefixed with dollar signs since they will be evaluated at the time the object is constructed, right before the base class constructor is invoked. This technique allows, as in C++, some actual processing to be done on the base class arguments at construction time. The <b>this</b> argument to the base class constructor must not be specified for it is automatically generated by stooop.
217
218<p>Sample code for a derived class constructor with base class constructor arguments processing:
219
220<pre>class circle {
221    proc circle {this x y} shape {
222        [expr round($x)] [expr round($y)]
223    } {
224        # constructor implementation
225    }
226}</pre>
227
228The base class(es) constructor(s) is(are) automatically invoked before the derived class constructor body is evaluated. Thus layered object construction occurs in the same order as in C++.
229
230<p>Variable length arguments are a special case and depend on both the derived class constructor arguments and those of the base class.
231
232<p>If both derived and base class constructors take a variable number of arguments (through the <i>args</i> special argument (see Tcl proc manual page)), the base class constructor will also see the variable arguments part as separate arguments. In other words, the following works as expected:
233
234<pre>class base {}
235proc base::base {this parameter args} {
236    array set options $args
237}
238class derived {}
239proc derived::derived {this parameter args} base {
240    $parameter $args
241} {}
242new derived someData -option value -otherOption otherValue</pre>
243
244Actually, if you want to get fancy, to allow some processing on the derived class constructor variable arguments, the last element (and only the last) of the derived class constructor arguments is considered variable if it contains the string <i>$args</i>. For example:
245
246<pre>class base {
247    proc base {this parameter args} {
248        array set options $args
249    }
250}
251class derived {
252    proc derived {this parameter args} base {
253        $parameter [process $args]
254    } {}
255    proc process {arguments} {
256        # do some processing on arguments list
257        return $arguments
258    }
259}
260new derived someData -option value -otherOption otherValue</pre>
261
262<h5><a name="destructor"></a>Destructor</h5>
263
264The destructor is used to clean up an object before it is removed from memory. The destructor is invoked by the <a href="#delete">delete</a> operator when an object of the class is deleted. The destructor is named as in C++ (for example, the shape constructor fully qualified name is <i>shape::~shape</i>).
265
266<p>The destructor always takes the object identifier (a unique value previously generated and returned by the operator new) as the only parameter, which must be named <b>this</b>.
267
268<p>The base class(es) destructor(s) is(are) invoked at the end of the derived class destructor body. Thus layered object destruction occurs in the same order as in C++.
269
270<p>Sample code of a class destructor:
271
272<pre>class shape {
273    proc ~shape {this} {
274        # implementation here
275    }
276}</pre>
277
278Contrary to C++, a destructor cannot (nor does it need to) be <a href="#virtual">virtual</a>. Even if it does nothing, a destructor <b>must</b> always be defined.
279
280<h5><a name="proceduresnonstatic"></a>Non static</h5>
281
282A <i>non static</i> member procedure performs some action on an object of a class. The member procedure is named as a member function in C++ (for example, the shape class move member procedure is known as <i>shape::move</i> in the Tcl global namespace).
283
284<p>The member procedure always takes the object identifier (a unique value generated and returned by the operator new) as the first parameter, plus eventually additional parameters as in the normal Tcl proc command. Arguments with default values are allowed, and so are variable number of arguments. In all cases, the first parameter must be named <b>this</b>.
285
286<p>Sample code of a member procedure:
287
288<pre>proc shape::move {this x y} {
289    set ($this,x) $x
290    set ($this,y) $y
291    draw $this       ;# invoke another member procedure
292}</pre>
293
294A non static member procedure may be a <a href="#virtual">virtual</a> procedure.
295
296<h5><a name="proceduresstatic"></a>Static</h5>
297
298A <i>static</i> member procedure performs some action independently of the individual objects of a class. The member procedure is named as a member function in C++ (for example, the shape class add static member procedure is defined as <i>shape::add</i> outside its class definition, <i>add</i> inside).
299
300<p>However, with stooop, there is no static specifier: a member procedure is considered static if its first parameter is not named <b>this</b>. Arguments to the procedure are allowed as in the normal Tcl proc command. Arguments with default values are also allowed, and so are variable number of arguments.
301
302<p>Sample code of a static member procedure:
303
304<pre>proc shape::add {newShape} {
305    # append new shape to global list of shape
306    lappend ($shapes) $newShape
307}</pre>
308
309Often, static member procedures access static member data (see <a href="#datastatic">Static Member Data</a>).
310
311<p>A static member procedure may not be a virtual procedure.
312
313<h5><a name="copy"></a>Copy constructor</h5>
314
315<i><b>Note</b>: if you never create objects by copying (which is generally the case), you can skip this section.</i>
316
317<p>Let us start by making it clear that stooop generates a default copy constructor whenever a class main constructor is defined. This default copy constructor just performs a simple per data member copy, as does C++.
318
319<p>The user defined class copy constructor is optional as in C++. If it exists, it will be invoked (instead of the default copy constructor) when the operator <a href="#new">new</a> is invoked on an object of the class or a derived class.
320
321<p>The copy constructor takes 2 arguments: the <i>this</i> object identifier used to initialize the data members of the object to be copied to, and the <i>copy</i> identifier of the object to be copied from, as in:
322
323<pre>proc plane::plane {this copy} {
324    set ($this,wingspan) $($copy,wingspan)
325    set ($this,length) $($copy,length)
326    set ($this,engine) [new $($copy,engine)]
327}</pre>
328
329As in regular member procedures, the first parameter name must be <b>this</b>, whereas the second parameter must be named <b>copy</b> to differentiate from the class constructor. In other words, the copy constructor always takes 2 and only 2 arguments (named this and copy).
330
331<p>The copy constructor must be defined when the default behavior (straightforward data members copy) (see the <a href="#new">new operator</a>) is not sufficient, as in the example above. It is most often used when the class object contains sub objects. As in C++ when sub objects are referenced through pointers, only the sub object identifiers (see them as pointers) are copied when an object is copied, not the objects they point to. It is then necessary to define a copy procedure that will actually create new sub objects instead of just defaulting to copying identifiers.
332
333<p>If the class has one or more base classes, then the copy constructor must pass arguments to the base class(es) constructor(s), just as the main constructor does, as in the following example:
334
335<pre>class ship {
336    proc ship {this length} {}
337}
338class carrier {}
339proc carrier::carrier {this length} ship {$length} {}
340proc carrier::carrier {this copy} ship {
341    $ship::($copy,length)
342} {
343    set ship::($this,planes) {}
344    foreach plane $ship($copy,planes) {                   ;# copy all the planes
345        lappend ship($this,planes) [new $plane]
346    }
347}</pre>
348
349The stooop library checks that the copy constructor properly initializes the base class(es) through its(their) constructor(s) by using the regular constructor as reference. Obviously and consequently, stooop also checks that the regular constructor is defined prior to the copy constructor.
350
351<p>If you use <a href="#array">member arrays</a>, you must copy them within the copy constructor, as they are not automatically handled by stooop, which only knows <a href="#data">member data</a> in the automatically generated default copy constructor.
352
353<h4><a name="data"></a>Member data</h4>
354
355All class and object data is stored in an associative array local to the class namespace (remember, a class is actually a namespace). The array name is empty, and the corresponding Tcl variable declaration is automatically inserted within class namespace and procedures (but you do not need to worry about this transparent operation).
356
357<p>Sample code:
358
359<pre>class shape {}
360proc shape::shape {this x y} {
361    # set a few members of the class namespace empty named array
362    set ($this,x) $x
363    set ($this,y) $y
364    # now read them
365    puts "coordinates: $($this,x), $($this,y)"
366}</pre>
367In order to access other classes data, whether they are base classes or
368not, a fully qualified name is always required, whereas no special declaration
369(global, variable, ...) is required.
370<p>Sample code:
371<pre>proc circle::circle {this x y diameter} shape {$x $y} {
372    set ($this,diameter) $diameter
373    puts "coordinates: $shape::($this,x), $shape::($this,y)"
374}</pre>
375
376<h5><a name="datanonstatic"></a>Non static</h5>
377
378Non static data is indexed within the class array by prepending the object identifier (return value of the <i>new</i> operator) to the actual member name. A comma is used to separate the identifier and the member name.
379
380<p>Much as an object pointer in C++ is unique, the object identifier in <i>stooop</i> is also unique. Access to any base class data is thus possible by directly indexing the base class array.
381
382<p>Sample code:
383
384<pre>proc shape::shape {this x y} {
385    set ($this,x) $x
386    set ($this,y) $y
387}
388proc circle::circle {this x y diameter} shape {$x $y} {
389    set ($this,diameter) $diameter
390}
391proc circle::print {this} {
392    puts "circle $this data:"
393    puts "diameter: $($this,diameter)"
394    puts "coordinates: $shape::($this,x), $shape::($this,y)"
395}</pre>
396
397<h5><a name="datastatic"></a>Static</h5>
398
399<i>Static</i> (as in C++) data members are simply stored without prepending the object identifier to the member name, as in:
400
401<pre>proc shape::register {newShape} {
402    lappend (list) $newShape ;# append new shape to global list of shapes
403}</pre>
404
405<h3><a name="keywords"></a>Commands</h3>
406
407Only 4 new commands <a href="#class">class</a>, <a href="#new">new</a>, <a href="#delete">delete</a> and <a href="#virtual">virtual</a> need to be known in order to use <i>stooop</i>. Furthermore, their meaning should be obvious to C++ programmers. There is also a <a href="#classof">classof</a> command that you can use if you need RTTI (runtime type identification).
408
409<h4><a name="class"></a>class</h4>
410
411The <b>class</b> command introduces a new class declaration.
412
413<p>A class is also a namespace although you do not need to worry about it, but it does have some nice side effects. The following code works as expected:
414
415<pre>class shape {
416    set (list) {} ;# initialize list of shapes, a static data member
417    proc shape {this x y} {
418        lappend (list) $this             ;# keep track of new shapes
419    }
420    ...
421}</pre>
422
423This works because all data for the class (static and non static) is held in the empty named array, which the class command declares as a variable (see the corresponding Tcl command) for the class namespace and within every member procedure.
424
425<p>Starting with version 3.2, nested classes are allowed, which makes the following code possible:
426
427<pre>class car {
428    proc car {this manufacturer type} {
429        set ($this,wheels) [list\
430            [new wheel 18] [new wheel 18] [new wheel 18] [new wheel 18]\
431        ]
432        ...
433    }
434    ...
435    class part {
436        ...
437    }
438    class wheel {
439        proc wheel {this diameter} car::part {} {
440            set ($this,diameter) $diameter
441            ...
442        }
443        proc print {this} {
444            puts "wheel of $($this,diameter) diameter"
445        }
446        ...
447    }
448}</pre>
449
450There is quite a lot to say about the example above.
451
452<p>First, why would I use a nested class? Because it is cleaner that creating <i>carPart</i> and <i>carWheel</i> classes and saves on global namespace pollution.
453
454<p>Second, why does "<i>new wheel</i>" work from inside the car constructor? Because it invokes the <i>wheel::wheel</i> constructor, visible from the car namespace.
455
456<p>Third, why can't I simply derive wheel from <i>part</i> instead of <i>car::part</i>? Well, you must fully qualify the class that you derive from because the <i>part::part</i> constructor is not visible from within the wheel namespace.
457
458<p>Whenever you have a problem with nested classes, think in terms of namespaces, as classes are indeed namespaces (it should be clear to you by now :-).
459
460<h4><a name="new"></a>new</h4>
461
462The <i>new</i> operator is used to create an object of a class, either by explicit construction, or by copying an existing object.
463
464<p>When explicitly creating an object, the first argument is the class name and is followed by the arguments needed by the class constructor. New when invoked generates a unique identifier for the object to be created. This identifier is the value of the <b>this</b> parameter, first argument to the class constructor, which is invoked by new.
465
466<p>Sample code:
467
468<pre>proc shape::shape {this x y} {
469    set ($this,x) $x
470    set ($this,y) $y
471}
472set object [<b>new</b> shape 100 50]</pre>
473
474new generates a new object identifier, say 1234. shape constructor is then called, as in:
475
476<pre>shape::shape 1234 100 50</pre>
477
478If the class is derived from one or more base classes, the base class(es) constructor(s) will be automatically called in the proper order, as in:
479
480<pre>proc hydroplane::hydroplane {this wingspan length} plane {
481    $wingspan $length
482} boat {
483    $length
484} {}
485set object [<b>new</b> hydroplane 10 7]</pre>
486
487new generates a new object identifier, say 1234, plane constructor is called, as in:
488
489<pre>plane::plane 1234 10 7</pre>
490
491then boat constructor is called, as in:
492
493<p>boat::boat 1234 7
494
495<p>finally hydroplane constructor is called, as in:
496
497<p>hydroplane::hydroplane 1234 10 7
498
499<p>The new operator can also be used to copy objects when an object identifier is its only argument. A new object of the same class is then created, copy of the original object.
500
501<p>An object is copied by copying all its data members (but not including <a href="#array">member arrays</a>) starting from the base class layers. If the copy constructor procedure exists for any class layer, it is invoked by the <i>new</i> operator <b>instead</b> of the default data member copy procedure (see the <a href="#copy">copy constructor</a> section for examples).
502
503<p>Sample code:
504
505<pre>set plane [new plane 100 57 RollsRoyce]
506set planes [list $plane [new $plane] [new $plane]]</pre>
507
508<h4><a name="delete"></a>delete operator</h4>
509
510The <i>delete</i> operator is used to delete one or several objects. It takes one or more object identifiers as argument(s). Each object identifier is the value returned by <i>new</i> when the object was created. Delete invokes the class destructor for each object to be deleted.
511
512<p>Sample code:
513
514<pre>proc shape::shape {this x y} {}
515proc shape::~shape {this} {
516
517proc triangle::triangle {this x y} shape {$x $y} {}
518proc triangle::~triangle {this} {}
519
520proc circle::circle {this x y} shape {$x $y} {}
521proc circle::~circle {this} {}
522
523set circle [new circle 100 50]
524set triangle [new triangle 200 50]
525<b>delete</b> $circle $triangle</pre>
526
527circle identifier is set to, say 1234, triangle identifier is set to, say 1235. delete circle object first, circle destructor is invoked, as in:
528
529<pre>circle::~circle 1234</pre>
530
531then shape destructor is invoked, as in:
532
533<p>shape::~shape 1234
534
535<p>then delete triangle object...
536
537<p>For each object class, if it is derived from one or more base classes, the base class(es) destructor(s) are automatically called in reverse order of the construction order for base class(es) constructor(s), as in C++.
538
539<p>If an error occurs during the deletion process, an error is returned and the remaining delete argument objects are left undeleted.
540
541<h4><a name="virtual"></a>virtual specifier</h4>
542
543The <i>virtual</i> specifier may be used on member procedures to achieve dynamic binding. A procedure in a base class can then be redefined (overloaded) in the derived class(es).
544
545<p>If the base class procedure is invoked on an object, it is actually the derived class procedure which is invoked, if it exists<b>*</b>. If the base class procedure has no body, then it is considered to be a pure virtual and the derived class procedure is always invoked.
546
547<p><b>*</b> <i>as in C++, virtual procedures invoked from the base class constructor result in the base class procedure being invoked, not the derived class procedure. In stooop, an error always occurs when pure virtual procedures are invoked from the base class constructor (whereas in C++, behavior is undefined).</i><br>
548<i>* but there is a small difference with C++ behavior: for a virtual procedure to keep his nature down the derived classes hierarchy, it must be defined at each derivation level. That is, the virtual nature may be lost, for example in indirectly derived classes (see example below). Fixing this difference would have a non negligible impact on performance for a small gain in usefulness.</i>
549
550<p>Sample code:
551
552<pre>class shape {
553    proc shape {this x y} {}
554    # pure virtual draw: must be implemented in derived classes
555    <b>virtual</b> proc draw {this}
556    <b>virtual</b> proc transform {this x y} {
557        # base implementation
558    }
559}
560class circle {}
561proc circle::circle {this x y} shape {$x $y} {}
562proc circle::draw {this} {
563    # circle specific implementation
564}
565proc circle::transform {this} {
566    shape::_transform $this ;# use base class implementation
567    # add circle specific implementation here...
568}
569
570lappend shapes [new circle 100 50]
571foreach object $shapes {
572    # draw and move each shape
573    shape::draw $object
574    shape::move $object 20 10
575}</pre>
576
577It is possible to invoke a virtual procedure as a non virtual one, which is handy when the derived class procedure must use the base class procedure. In this case, directly invoking the virtual base class procedure would result in an infinite loop. The non virtual base class procedure name is simply the virtual procedure name with 1 underscore ( _ ) prepended to the member procedure name (see sample code above).
578
579<p>Constructors, destructors and static member procedures cannot be <i>virtual</i>.
580
581<p>Sample code highlighting small difference with C++:
582
583<pre>class A {
584    proc A {this} {}
585    proc ~A {this} {}
586    <b>virtual</b> proc p {this} {puts A}
587}
588class B {
589    proc B {this} A {} {}
590    proc ~B {this} {}
591}
592class C {
593    proc C {this} B {}{}
594    proc ~C {this} {}
595    <b>virtual</b> proc p {this} {puts C}
596}
597
598set object [new C]
599A::p $object ;# prints "A" instead of "C"
600
601<b>virtual</b> proc B::p {this} {puts B}
602
603A::p $object ;# now prints "C"</pre>
604
605<h4><a name="classof"></a>classof operator</h4>
606
607The <i>classof</i> command takes an object identifier as its only argument. It returns the class name of the object (name used with new when the object was created). Thus if needed, RTTI (runtime type identification) can be used as in C++, for example to create "virtual constructors".
608
609<pre>proc shape::shape {this x y} {}
610set id [new shape 100 50]
611puts "object $id class name is [<b>classof</b> $id]"</pre>
612
613<h3><a name="package"></a>Package</h3>
614
615For general information about the Tcl (version 7.5 and above) <i>package</i> facilities, refer to the corresponding manual pages.
616
617<h4><a name="installation"></a>Installation</h4>
618
619A <i>pkgIndex.tcl</i> file is provided so that stooop and the <a href="#switched">switched</a> class can be installed as a package. Refer to the <a href="INSTALL">INSTALL</a> file for complete instructions and examples.
620
621<h4><a name="creation"></a>Creation</h4>
622
623Before creating a package that uses stooop, stooop itself <b>must</b> be installed as a package (see above).
624
625<p>If you have created an object oriented library which uses stooop, you may want to make a package out of it. Unfortunately, using the default Tcl <i>pkg_mkIndex</i> procedure (see the corresponding manual page) will not work.
626
627<p>Stooop checks that a base class constructor is defined before any of its derived classes constructors. Thus, the first time a derived class object is created, the base class definition file must be sourced to avoid an error. The specific <i>mkpkgidx.tcl</i> utility handles such cases and must be used to create stooop compatible package index files.
628
629<p>Let us suppose that you created a library with different classes spread in different source files: <i>lib1.tcl</i>, <i>lib2.tcl</i>, ..., <i>libn.tcl</i>. Of course, some of these files may contain base classes for derived classes in other files. As recommended in the pkg_mkIndex Tcl manual page, each source file should contain a <b>package provide</b> command (although it seems to be needed only in the first source file). For example, if your package name is <i>foo</i> and the version <i>1.2</i>, the following line should appear around the beginning of each of the libn.tcl files:
630
631<pre>package provide foo 1.2</pre>
632
633It is now time to create the <i>pkgIndex.tcl</i> file, which is the missing piece for your foo package, with the <i>mkpkgidx.tcl</i> utility. The syntax is:
634
635<pre>interpreter mkpkgidx.tcl packageName file [file ...]</pre>
636
637where <i>interpreter</i> can be either tclsh or wish depending on whether your library uses Tk or not.
638
639<p>Enter the following command in the directory where the libn.tcl files reside:
640
641<pre>$ tclsh mkpkgidx.tcl foo lib1.tcl lib2.tcl ... libn.tcl</pre>
642
643or
644
645<pre>$ wish mkpkgidx.tcl foo lib1.tcl lib2.tcl ... libn.tcl</pre>
646
647For this to work, the source files must be ordered so that base classes are defined before any of their derived classes. If not the case, such errors are automatically caught by the stooop package index utility, which uses the stooop library itself.
648
649<p>If your package requires other packages and you do not wish to add the corresponding "package require" to your package source files, use the -p option, as in:
650
651<pre>$ wish mkpkgidx.tcl -p ppp.1 -p qqq -p rrr.3.2 foo lib1.tcl lib2.tcl ... libn.tcl</pre>
652
653Note that you may use as many -p option / value pairs as needed. Each package name is optionally followed by its version number after a . separator. If specified, the version number follows the same rules as the "package require" Tcl command. Of course, each specified package must be installed and working properly before attempting the mkpkgidx.tcl utility.
654
655<p>Once this is done, a pkgIndex.tcl file will have been created in the current directory. To install the package, enter for example:
656
657<pre>$ mkdir /usr/local/lib/foo
658$ cp pkgIndex.tcl lib1.tcl lib2.tcl ... libn.tcl /usr/local/lib/foo/</pre>
659
660You may of course install the foo package in another directory: refer to the pkg_mkIndex Tcl manual page for further instructions.
661
662<p>Now in order to use your newly created packaged library in your application, just insert the following 3 lines at the beginning of the application source file:
663
664<pre>package require stooop
665namespace import stooop::*
666package require foo 1.2</pre>
667
668<h3><a name="examples"></a>Examples</h3>
669
670<h4><a name="parallel"></a>Parallel with C++</h4>
671
672For C++ programmers, this simple parallel with C++ may make things easier to understand. First without virtual functions:
673
674<p><b>C++:</b>
675
676<pre>    class className {
677    public:
678        someType someMember;
679        className(someType parameter)
680        {
681            someMember = parameter;
682        }
683        className(className &amp;object)
684        {
685            ...
686        }
687        doSomething(someType parameter);
688        ~className(void) {
689            ...
690        }
691    };
692    someType className::doSomething(someType parameter)
693    {
694        ...
695    }
696    someType someValue;
697    className *someObject = new className(someValue);
698    someType a = someObject->doSomething(someValue);
699    someType b = someObject->someMember;
700    className *otherObject = new className(*someObject);
701    delete someObject;</pre>
702
703<b>(stooop'd up :) Tcl:</b>
704
705<pre>    class className {
706        proc className {this parameter} {
707            # new keeps track of object identifiers and passes a unique one
708            # to the constructor
709            set ($this,someMember) $parameter
710        }
711        proc className {this copy} {
712            # copy constructor
713            ...
714        }
715        proc ~className {this} {
716            # delete invokes this procedure then takes care of deallocating
717            # className array data members for this object identifier
718            ...
719        }
720    }
721    proc className::doSomething {this parameter} {
722        ...
723    }
724    set someObject [new className $someValue]
725    # invokes className::className
726    set a [className::doSomething $someObject $someValue]
727    set b $className::($someObject,someMember)
728    # copy object, className copy constructor is invoked
729    set otherObject [new $someObject]
730    delete $someObject
731    # invokes className::~className then frees members data</pre>
732
733Now, with virtual functions:
734
735<p><b>C++:</b>
736
737<pre>    class baseClassName {
738    public:
739        virtual void doSomething(someType) {}
740        baseClassName(void) {}
741        virtual ~baseClassName(void) {}
742    };
743    class derivedClassName: public baseClassName {
744    public:
745        void doSomething(someType);
746        derivedClassName(void) {}
747        ~derivedClassName(void) {}
748    };
749    void derivedClassName::doSomething(someType parameter)
750    {
751        ...
752    }
753    derivedClassName *someObject = new derivedClassName();
754    someObject->doSomething(someValue);      // derived function actually called
755    cout &lt;&lt; typeid(*someObject).name() &lt;&lt; endl;       // print object class name
756    delete someObject;                        // derived destructor called first</pre>
757
758<b>Tcl with stooop:</b>
759
760<pre>    class baseClassName {
761        proc baseClassName {this} {
762            # sub-class is remembered so that virtual procedures may be used
763            ...
764        }
765        proc ~baseClassName {this} {
766            # cleanup at base level here...
767        }
768        virtual proc doSomething {this parameter} {
769            # derived class procedure with the same name may be invoked
770            # any code that follows is not executed if this procedure is
771            # overloaded in derived class
772            ...
773        }
774    }
775    class derivedClassName {
776        proc derivedClassName {this} baseClassName {} {
777            # base class constructor is automatically invoked
778            ...
779        }
780        proc ~derivedClassName {this} {
781            # cleanup at derived level here...
782            # base class destructor is automatically invoked
783        }
784    }
785    proc derivedClassName::doSomething {this parameter} {
786        # code that follows is executed when base class procedure is called
787        ...
788    }
789    set someObject [new derivedClassName]
790    # access object as base object, derived class procedure is actually invoked
791    baseClassName::doSomething $someObject $someValue
792    puts [classof $someObject]                        ;# print object class name
793    delete $someObject                                          ;# delete object</pre>
794
795<h4><a name="graphical"></a>Graphical demonstration</h4>
796
797A demonstration using the Composite pattern from the great book Design Patterns, Elements of Reusable Object Oriented Software, which I heartily recommend.
798
799<p>The pattern is used to define a class hierarchy of the graphic base class, picture, oval and rectangle derived classes. A picture object can contain any number of other graphic objects, thus allowing graphical composition.
800
801<p>The following paragraphs drawn from the book best describe what the Composite pattern does:
802
803<blockquote><i>Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.</i>
804
805<p><i>The key to the Composite pattern is an abstract class that represents both primitives and their containers. For the graphic system, this class is Graphic. Graphic declares operations like Draw that are specific to graphical objects. It also declares operations that all composite objects share, such as operations for accessing and managing its children.</i>
806
807<p><i>Gamma/Helm/Johnson/Vlissides, DESIGN PATTERNS, ELEMENTS OF REUSABLE OBJECT-ORIENTED SOFTWARE, (c) 1995 by Addison-Wesley Publishing Company, Reprinted by permission of Addison-Wesley Publishing Company, Inc.</i></blockquote>
808
809Instructions:
810
811<p>Run gdemo as in:
812
813<pre>$ wish gdemo</pre>
814
815Several buttons are placed below a canvas area. Picture, Rectangle and Oval are used to create Graphic objects. Clear is used to delete all the objects created so far, Exit is self explanatory.
816
817<p>A Picture object can contain any number of Graphic objects, such as other Picture objects, Rectangle objects, ...
818
819<p>For each Graphic object, the point used for moving and for the object coordinates is the upper left corner of the object.
820
821<p>First create a Picture object by clicking on the Picture button. Move the red rectangle that appears by drag clicking on any of its edges. Then create a Rectangle object by clicking on the Rectangle button. Drag the Rectangle object in the Picture object, it is then a child of the Picture object.
822
823<p>Move the Picture object to verify that its Rectangle child moves along.
824
825<p>Create another Picture object and place an Oval object within.
826
827<p>Move that Picture object to verify that its Oval child moves along.
828
829<p>Now move the upper left corner of that last Picture within the first Picture area.
830
831<p>Then move that Picture to verify that all the Graphic objects move along.
832
833<h4><a name="widget"></a>Widget class</h4>
834
835A widget usually can take a variable number of option / value pairs as arguments when created and any time later when configured. It is a good application for the variable number of arguments technique.
836
837<p>Sample code (without error checking):
838
839<pre>class widget {
840    proc widget {this parent args} {
841        # create Tk widget(s)
842        # set widget options default in an array
843        array set options {-background white -width 10}
844        array set options $args              ;# then overwrite with user options
845        eval configure $this [array get options]               ;# then configure
846    }
847    virtual proc configure {this args} {
848        foreach {option value} $args {
849            switch -- $option {
850                -background {             ;# filter widget specific options here
851                    set ($this,background) $value
852                    # configure Tk widget(s)
853                }
854                ...
855            }
856        }
857    }
858}
859
860class gizmo {}
861proc gizmo::gizmo {this parent args} widget {$parent $args} {
862    # create more Tk widget(s)
863    # set gizmo options default in an array
864    array set options {-spacetimecoordinates {0 0 0 now}}
865    array set options $args                  ;# then overwrite with user options
866    eval ownConfigure $this [array get options]                ;# then configure
867}
868proc gizmo::ownConfigure {this args} {
869    foreach {option value} $args {
870        switch -- $option {                ;# filter gizmo specific options here
871            -spacetimecoordinates {
872                set ($this,location) $value
873                # configure Tk widget(s)
874            }
875            ...
876        }
877    }
878}
879proc gizmo::configure {this args} {
880    eval ownConfigure $this $args                    ;# configure at gizmo level
881    eval widget::_configure $this $args             ;# configure at widget level
882}
883
884new gizmo . -width 20 -spacetimecoordinates {1p 10ly 2p 24.2y}</pre>
885
886In this example, invalid (unknown) options are simply ignored.
887
888<h4><a name="array"></a>Member array</h4>
889
890A true member array is not possible, as member data is already held in an array.
891<br>But there are 2 ways to get around the problem:<ul>
892  <li>embed the array and its index in member data
893  <li>use a namespace array for possibly better performance
894</ul>
895
896<p>For example, when embedding in member data:
897
898<pre>class container {
899    proc container {this} {}
900    proc ~container {this} {}
901    proc container::add {this index value} {
902        set ($this,array,$index) $value
903    }
904}</pre>
905
906<p>With a namespace array, use a name specific to the object, including the object identifier, and do not forget to delete the array in the destructor, as the following example shows:
907
908<pre>class container {
909    proc container {this} {}
910    proc ~container {this} {
911        variable ${this}array
912        unset ${this}array
913    }
914    proc container::add {this index value} {
915        variable ${this}array
916        set ${this}array($index) $value
917    }
918}</pre>
919
920Memory management of the array is the programmer's responsibility, as is its duplication when copying objects. For example, use the following code if you ever copy objects with member arrays:
921
922<pre>class container {
923    proc container {this} {                                  ;# main constructor
924        ...
925    }               ;# default copy constructor has been generated at this point
926    proc container {this copy} {      ;# copy constructor (replaces default one)
927        variable ${this}array
928        variable ${copy}array
929        array set ${this}array [array get ${copy}array]     ;# copy member array
930    }
931    ...
932}</pre>
933
934<h3><a name="utility"></a>Utility classes</h3>
935
936<h4><a name="switched"></a>switched</h4>
937
938<i><b>Note</b>: if you have been using scwoop (a stooop based mega widget extension to the Tk widget library), you must certainly know about the composite class. The switched class is a generic (not widget oriented) derivative of the composite class.</i>
939
940<p>Find the complete documentation <a href="switched.html">here</a>.
941
942<h3><a name="debugging"></a>Debugging</h3>
943
944As stooop is meant to be lean and fast, no checking is done during run-time, that is after all classes and their procedures have been defined.
945
946<p>Starting from version 3.3, debugging aids were added to the stooop library (still held in a single file). Member checking insures that basic object oriented concepts and rules are applied. Tracing provides means for member procedures and data access logging to a file or to the screen.
947
948<p>The above features are triggered and configured using environment variables. When not in use, they have absolutely no impact on stooop's performance (however, if you are really picky, you could say that since the stooop.tcl file has grown larger, load time got longer :).
949
950<p>Please note that any stooop debugging environment variable must be set <b>prior</b> to the stooop library being loaded:
951
952<pre>$ STOOOPTRACEDATA=stdout
953$ export STOOOPTRACEDATA
954$ tclsh myfile.tcl</pre>
955around the beginning of myfile.tcl:
956<pre>...
957set env(STOOOPCHECKPROCEDURES) 1
958source stooop.tcl
959namespace import stooop::*
960set env(STOOOPCHECKDATA) 1
961...</pre>
962
963In the example above, data tracing is enabled as well as procedure checking, but data checking is not turned on.
964
965<h4><a name="check"></a>Member check</h4>
966
967Both procedure and data member checking can be activated by setting the single environment variable STOOOPCHECKALL to a true value (<i>1</i>, <i>true</i> or <i>on</i>). Of course only one of those features can be activated as described below.
968
969<p><i>Note: if you have an idea about any other thing that could be checked in the following sections, please share it with <a href="mailto:jfontain@free.fr">me</a>.</i>
970
971<h5><a name="procedurecheck"></a>Procedure</h5>
972
973Procedure checking is activated by setting the environment variable STOOOPCHECKPROCEDURES to a true value. The stooop library will then generate an error while the application is running in the following cases:
974
975<ul>
976  <li>an invalid <i>this</i> parameter (a non existing object identifier) is passed as argument to a non static member procedure
977  <li>the object identified by the <i>this</i> parameter passed as argument to a class non static member procedure is neither an instance of the procedure class nor an instance of a derived class (at any level of derivation) of the procedure class.
978  <li>a pure interface class (a class with at least 1 pure virtual member procedure) is instanciated
979</ul>
980
981<h5><a name="datacheck"></a>Data</h5>
982
983Procedure checking is activated by setting the environment variable STOOOPCHECKDATA to a true value. The stooop library will then generate an error while the application is running in the following cases:
984
985<ul>
986  <li>in a class namespace but outside a member procedure, a data member of another class is written or unset
987  <li>in a class member procedure (static or not), a data member of another class is written or unset
988  <li>in a non static member procedure, a data member of an object different from the object identified by the <i>this</i> parameter passed as argument is written or unset
989</ul>
990
991<h4><a name="trace"></a>Member trace</h4>
992
993Tracing is activated by setting a specific environment variable to either <i>stdout</i>, <i>stderr</i> or any file name that can be created and written to by the user. Setting the STOOOPTRACEALL variable enables both procedure and data tracing. Of course only one of those features can be activated as described below.
994
995<h5><a name="proceduretrace"></a>Procedure</h5>
996
997Procedure tracing is activated by setting the environment variable STOOOPTRACEPROCEDURES to either <i>stdout</i>, <i>stderr</i> or a file name. The stooop library will then output to the specified channel 1 line of informational text for each member procedure invocation.
998
999<p>The user can define the output format by redefining the STOOOPTRACEPROCEDURESFORMAT (look at the beginning of the stooop.tcl file for the default format). The following substitutions will be performed prior to the output:
1000
1001<ul>
1002  <li><b>%C</b> by the fully qualified class name
1003  <li><b>%c</b> by the class name (tail of the fully qualified class name)
1004  <li><b>%P</b> by the fully qualified procedure name
1005  <li><b>%p</b> by the procedure name (tail of the fully qualified procedure name)
1006  <li><b>%O</b> by the object identifier (<i>this</i> value)
1007  <li><b>%a</b> by the remaining procedure arguments (not including <i>this</i>)
1008</ul>
1009
1010At the time this document is being written, the default format is:
1011
1012<pre>class: %C, procedure: %p, object: %O, arguments: %a</pre>
1013
1014example output from the gdemo application:
1015
1016<pre>class: picture, procedure: constructor, object: 1, arguments: .canvas
1017class: graphic, procedure: constructor, object: 1, arguments: .canvas 1
1018class: rectangle, procedure: constructor, object: 2, arguments: .canvas
1019class: graphic, procedure: constructor, object: 2, arguments: .canvas 2
1020class: graphic, procedure: moveTo, object: 2, arguments: 13 4
1021class: graphic, procedure: _moveTo, object: 2, arguments: 13 4
1022class: graphic, procedure: moveTo, object: 2, arguments: 18 9
1023class: graphic, procedure: add, object: 1, arguments: 2
1024class: picture, procedure: add, object: 1, arguments: 2
1025class: graphic, procedure: add, object: 2, arguments: 2
1026class: rectangle, procedure: add, object: 2, arguments: 2
1027class: picture, procedure: destructor, object: 1, arguments:
1028class: graphic, procedure: destructor, object: 1, arguments:
1029class: rectangle, procedure: destructor, object: 2, arguments:
1030class: graphic, procedure: destructor, object: 2, arguments:</pre>
1031
1032<h5><a name="datatrace"></a>Data</h5>
1033
1034Data tracing is activated by setting the environment variable STOOOPTRACEDATA to either <i>stdout</i>, <i>stderr</i> or a file name. The stooop library will then output to the specified channel 1 line of informational text for each member data access. By default, all read, write and unsetting accesses are reported, but the user can set the STOOOPTRACEDATAOPERATIONS environment variable to any combination of the <i>r</i>, <i>w</i> and <i>u</i> letters for more specific tracing (please refer to the <i>trace</i> Tcl manual page for more information).
1035
1036<p>Note that operations internal to the stooop library, such as automatic unsetting of data members during objects destruction do not appear in the trace.
1037
1038<p>The user can define the output format by redefining the STOOOPTRACEDATAFORMAT (look at the beginning of the stooop.tcl file for the default format). The following substitutions will be performed prior to the output:
1039
1040<ul>
1041  <li><b>%C</b> by the fully qualified class name
1042  <li><b>%c</b> by the class name (tail of the fully qualified class name)
1043  <li><b>%P</b> by the fully qualified procedure name
1044  <li><b>%p</b> by the procedure name (tail of the fully qualified procedure name)
1045  <li><b>%A</b> by the fully qualified array name
1046  <li><b>%m</b> by the data member name (right after the <i>this,</i> array name part for a non static data member)
1047  <li><b>%O</b> by the object identifier (<i>this</i> value or empty for a static procedure)
1048  <li><b>%o</b> by the access operation (<i>read</i>, <i>write</i> or <i>unset</i>)
1049  <li><b>%v</b> by the new or current value (empty for an <i>unset</i> operation)
1050</ul>
1051
1052At the time this document is being written, the default format is:
1053
1054<pre>class: %C, procedure: %p, array: %A, object: %O, member: %m, operation: %o, value: %v</pre>
1055
1056example output from the gdemo application:
1057
1058<pre>class: graphic, procedure: constructor, array: graphic::, object: 1, member: canvas, operation: write, value: .canvas
1059class: graphic, procedure: constructor, array: graphic::, object: 1, member: item, operation: write, value: 1
1060class: picture, procedure: constructor, array: picture::, object: 1, member: graphics, operation: write, value: 
1061class: picture, procedure: moveTo, array: graphic::, object: 1, member: canvas, operation: read, value: .canvas
1062class: picture, procedure: moveTo, array: graphic::, object: 1, member: item, operation: read, value: 1
1063class: picture, procedure: moveBy, array: picture::, object: 1, member: graphics, operation: read, value: 
1064class: graphic, procedure: _moveBy, array: graphic::, object: 1, member: canvas, operation: read, value: .canvas
1065class: graphic, procedure: _moveBy, array: graphic::, object: 1, member: item, operation: read, value: 1
1066class: graphic, procedure: constructor, array: graphic::, object: 2, member: canvas, operation: write, value: .canvas
1067class: graphic, procedure: constructor, array: graphic::, object: 2, member: item, operation: write, value: 2
1068class: graphic, procedure: _moveTo, array: graphic::, object: 2, member: canvas, operation: read, value: .canvas
1069class: graphic, procedure: _moveTo, array: graphic::, object: 2, member: item, operation: read, value: 2
1070class: graphic, procedure: _moveTo, array: graphic::, object: 2, member: canvas, operation: read, value: .canvas
1071class: graphic, procedure: _moveTo, array: graphic::, object: 2, member: item, operation: read, value: 2
1072class: graphic, procedure: _moveTo, array: graphic::, object: 2, member: canvas, operation: read, value: .canvas
1073class: graphic, procedure: _moveTo, array: graphic::, object: 2, member: item, operation: read, value: 2
1074class: graphic, procedure: _moveTo, array: graphic::, object: 2, member: canvas, operation: read, value: .canvas
1075class: graphic, procedure: _moveTo, array: graphic::, object: 2, member: item, operation: read, value: 2
1076class: picture, procedure: add, array: graphic::, object: 1, member: canvas, operation: read, value: .canvas
1077class: picture, procedure: add, array: graphic::, object: 1, member: item, operation: read, value: 2
1078class: picture, procedure: add, array: graphic::, object: 1, member: canvas, operation: read, value: .canvas
1079class: picture, procedure: add, array: graphic::, object: 1, member: item, operation: read, value: 1
1080class: graphic, procedure: destructor, array: graphic::, object: 1, member: canvas, operation: read, value: .canvas
1081class: graphic, procedure: destructor, array: graphic::, object: 1, member: item, operation: read, value: 1
1082class: graphic, procedure: destructor, array: graphic::, object: 2, member: canvas, operation: read, value: .canvas
1083class: graphic, procedure: destructor, array: graphic::, object: 2, member: item, operation: read, value: 2</pre>
1084
1085<h4><a name="objects"></a>Objects</h4>
1086
1087Objects checking can be activated by setting the single environment variable STOOOPCHECKOBJECTS to a true value. The following stooop namespace procedures then become available for debugging; <i>printObjects</i>, <i>record</i> and <i>report</i>.
1088
1089<p>Before outputting any data, all the object checking procedures print which procedure they were invoked from, or the namespace name if invoked from a namespace body or "<i>top level</i>" if invoked outside any procedure or namespace.
1090
1091<h5><a name="objects.printing"></a>Printing</h5>
1092
1093The <i>stooop::printObjects</i> procedure when invoked prints an ordered list of existing objects with their creation location (a fully qualified procedure name or "<i>top level</i>") after a <b>+</b> sign. The objects are printed in creation order, with the oldest (lowest identifier) first. The printObjects procedure takes an optional class pattern (as in the Tcl "<i>array names</i>" or "<i>string match</i>" commands) for limiting the output to objects of certain classes, as the following example shows (classes are assumed to exist and be valid):
1094
1095<pre>% new foo
10961
1097% stooop::printObjects
1098stooop::printObjects invoked from top level:
1099::foo(1) + top level
1100% new bar
11012
1102% stooop::printObjects
1103stooop::printObjects invoked from top level:
1104::foo(1) + top level
1105::bar(2) + top level
1106% new Foo
11073
1108% stooop::printObjects ::?oo
1109stooop::printObjects invoked from top level:
1110::foo(1) + top level
1111::Foo(3) + top level
1112% new barmaid
11134
1114% stooop::printObjects ::bar*
1115stooop::printObjects invoked from top level:
1116::bar(2) + top level
1117::barmaid(4) + top level</pre>
1118
1119Please note that all object classes are always fully qualified, so do not forget about the <b>::</b> header in the patterns.
1120
1121<h5><a name="objects.recording"></a>Recording</h5>
1122
1123By invoking the <i>stooop::record</i> procedure, you take a snapshot of all existing stooop objects at the time of invocation. Reporting can then be used at a later time to see which objects were created or deleted in the interval.
1124
1125<p>The record procedure does not take any arguments and it only prints its context of invocation.
1126
1127<h5><a name="objects.reporting"></a>Reporting</h5>
1128
1129The <i>stooop::report</i> procedure prints the created and deleted objects since the stooop::record procedure was invoked last. It optionally takes a pattern argument in order to limit the output to a specific set of classes, as for the printObjects procedure. A <b>+</b> sign is placed at the beginning of each created object description line in the output trace, followed by another <b>+</b> sign and the creation location (a fully qualified procedure name or "<i>top level</i>"). A <b>-</b> sign is placed at the beginning of each deleted object description line in the output trace, followed by another <b>-</b> sign, the deletion location (a fully qualified procedure name or "<i>top level</i>"), a <b>+</b> sign and the creation location (a fully qualified procedure name or "<i>top level</i>").
1130
1131<p>Reporting is typically used between 2 spots in the debugged application code: the first spot where a bunch of objects (which can include sub objects) are created, the second spot where all or most of these objects are supposed to be deleted. On the first spot, stooop::record is invoked whereas on the second spot, the stooop::report invocation will print the created and/or deleted objects, in other words the "object difference" between the 2 spots. In most cases, the programmer would expect a difference of 0 objects, sign of a well behaved application, memory wise.
1132
1133<p>Consider the following example:
1134
1135<pre>class foo {
1136    proc foo {this} {}
1137    proc ~foo {this} {}
1138}
1139class bar {
1140    proc bar {this} {
1141        new foo
1142    }
1143    proc ~bar {this} {}
1144}
1145stooop::record
1146delete [new bar]
1147stooop::report
1148stooop::record
1149delete 2
1150stooop::report</pre>
1151
1152It gives the following result:
1153
1154<pre>stooop::record invoked from top level
1155stooop::report invoked from top level:
1156+ ::foo(2) + ::bar::bar
1157stooop::record invoked from top level
1158stooop::report invoked from top level:
1159- ::foo(2) - top level + ::bar::bar</pre>
1160
1161Examining the printout, one can see that the bar class does not properly clean things up as the foo sub object is left undeleted.
1162
1163<h3><a name="notes"></a>Notes</h3>
1164
1165<h4><a name="design"></a>On design choices</h4>
1166
1167Performance would have to as good as possible.
1168
1169<p>A familiar C++ syntax should serve as a model (not all, though, I didn't feel like writing 700 pages of documentation :-).
1170
1171<p>Tcl being a non declarative language (which I really enjoy), stooop would have to try to comply with that approach.
1172
1173<p>Error checking would have to be strong with little impact on performance.
1174
1175<h4><a name="implementation"></a>On implementation</h4>
1176
1177For a Tcl only extension, I think performance is the main issue. The performance / functionality compromise was handled by moving as much processing as possible to the preprocessing stage, handled by the proc and virtual commands. Furthermore, all the costly error checking could be done there as well, having no impact on runtime performance.
1178
1179<p>The delete operation was greatly simplified, especially for classes that would require a virtual destructor in C++, by storing in an array the class of each object. It then became trivial to delete any object from its identifier only. This approach has an impact on memory use, though, but I consider that one is not very likely to create a huge number of objects in a Tcl application. Furthermore, a classof RTTI operator was then added with no effort.
1180
1181<p>Stooop learns class hierarchies through the constructor definition whichserves as an implementation as well, thus (kind of) better fitting the non declarative nature of Tcl.
1182
1183<p>All member data is public but access control is somewhat enforced by having to explicitly name the class layer of external data being accessed.
1184
1185<p>Since, for performance reasons, the stooop library performs very little checking during run-time (after all classes and their procedures were defined), debugging aids are provided starting from version 3.3. They attempt to insure that your code is well written in an object oriented sense. They also provide means for tracing data access and procedures.
1186
1187<h3><a name="misc"></a>Miscellaneous information</h3>
1188
1189For downloading other Tcl software (such as scwoop, moodss, ...), visit my <a href="http://jfontain.free.fr/">web page</a>.
1190
1191<p>Send your comments, complaints, ... to <a href="mailto:jfontain@free.fr">Jean-Luc Fontaine</a>.
1192
1193</body>
1194</html>
1195