The R Project SVN R

Rev

Rev 72016 | Rev 85532 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
60325 ripley 1
% File src/library/methods/man/refClass.Rd
68948 ripley 2
% Part of the R package, https://www.R-project.org
66564 maechler 3
% Copyright 2010-2014 R Core Team
60325 ripley 4
% Distributed under GPL 2 or later
5
 
52816 jmc 6
\name{ReferenceClasses}
56985 maechler 7
\title{Objects With Fields Treated by Reference (OOP-style)}
56186 murdoch 8
\alias{ReferenceClasses}
52816 jmc 9
\alias{setRefClass}
53003 jmc 10
\alias{getRefClass}
52960 jmc 11
\alias{initFieldArgs}
57841 jmc 12
\alias{initRefFields}
52960 jmc 13
\alias{activeBindingFunction-class}
14
\alias{defaultBindingFunction-class}
15
\alias{uninitializedField-class}
52816 jmc 16
\alias{refClassRepresentation-class}
52903 jmc 17
\alias{refObjectGenerator-class}
61058 jmc 18
\alias{refGeneratorSlot-class}
52816 jmc 19
\alias{refClass-class}
20
\alias{refObject-class}
52903 jmc 21
\alias{refMethodDef-class}
55578 jmc 22
\alias{refMethodDefWithTrace-class}
52846 jmc 23
\alias{SuperClassMethod-class}
56335 jmc 24
\alias{show,envRefClass-method}
52903 jmc 25
\alias{show,refMethodDef-method}
68626 jmc 26
\alias{show,externalRefMethod-method}
52816 jmc 27
\alias{show,refClassRepresentation-method}
68626 jmc 28
\alias{externalRefMethod}
29
\alias{externalRefMethod-class}
52816 jmc 30
\description{
71540 jmc 31
The software described here allows packages to define \emph{reference
32
  classes} that behave in the style of \dQuote{OOP} languages such as Java and
53003 jmc 33
C++.
71540 jmc 34
This model for OOP differs from the functional model implemented by S4
35
(and S3) classes and methods, in which methods are defined for generic
36
functions.
37
Methods for reference classes are \dQuote{encapsulated} in the class definition.
38
 
39
Computations with objects from reference classes invoke methods on them and
40
extract or set their fields, using  the \code{`$`} operator in \R.%$
53003 jmc 41
The field and method computations potentially modify the object.
42
All computations referring to the objects see the modifications, in contrast to
43
the usual functional programming model in \R.
71540 jmc 44
 
45
A call to
46
\code{setRefClass} in the source code for a package defines the class and returns a generator object.
47
Subsequent calls to the \code{$methods()} %$
48
method of the generator will define methods for the class.
49
As with functional classes, if the class is exported from the package,
50
it will be available when the package is loaded.
51
 
52
Methods are \R functions.  In their usual implementation, they refer to fields
53
and other methods of the class directly by name. See the section on
54
\dQuote{Writing Reference Methods}.
55
 
56
As with functional classes, reference classes can inherit from other
57
reference classes via a \code{contains=} argument to
58
\code{setRefClass}.  Fields and methods will be inherited, except where the
59
new class overrides method definitions.  See the section on \dQuote{Inheritance}.
60
 
52816 jmc 61
}
62
\usage{
52960 jmc 63
setRefClass(Class, fields = , contains = , methods =,
68627 jmc 64
     where =, inheritPackage =, ...)
52816 jmc 65
 
53003 jmc 66
getRefClass(Class, where =)
52816 jmc 67
}
68
\arguments{
69
  \item{Class}{
70
character string name for the class.
53669 jmc 71
 
72
In the call to \code{getRefClass()} this argument can also be any
71540 jmc 73
object from the relevant class.
74
 
52816 jmc 75
}
52960 jmc 76
  \item{fields}{
77
either a character vector of field names or
78
a named list of the fields.  The resulting fields will be accessed with reference semantics (see
71540 jmc 79
the  section on \dQuote{Reference Objects}).  If the argument is a list, each
80
element of the list should usually be the character string name of a class, in
81
which case the object in the field must be from that class or a
82
subclass.  An alternative, but not generally recommended, is to supply an  \emph{accessor
83
   function}; see the section on \dQuote{Implementation} for accessor
84
 functions and the related internal mechanism.
52960 jmc 85
 
86
Note that fields are distinct from
71540 jmc 87
slots.  Reference classes should not define class-specific slots. See
88
the note on slots in the
62255 jmc 89
\dQuote{Implementation} section.
52816 jmc 90
}
91
  \item{contains}{
92
optional vector of superclasses for this class.  If a superclass is
52846 jmc 93
also a reference class, the fields and class-based methods will be inherited.
52816 jmc 94
}
52960 jmc 95
  \item{methods}{
52816 jmc 96
a named list of function definitions that can be invoked on objects
52960 jmc 97
from this class.  These can also be created by invoking the
98
\code{$methods} method on the generator object returned. %$
99
See the section on \dQuote{Writing Reference Methods} for details.
71540 jmc 100
}
53068 jmc 101
 
71540 jmc 102
  \item{where}{
103
for \code{setRefClass}, the environment in which to store the class definition.  Should be
104
omitted in calls from a package's source code.
53068 jmc 105
 
71540 jmc 106
For \code{getRefClass}, the environment from which to search for the definition.  If the
107
package is not loaded or you need to be specific, use
108
\code{\link{asNamespace}} with the package name.
52816 jmc 109
}
68627 jmc 110
  \item{inheritPackage}{
111
Should objects from the new class inherit the package environment of a
112
contained superclass?  Default \code{FALSE}.  See the Section \dQuote{Inter-Package Superclasses
113
  and External Methods}.
114
} 
52816 jmc 115
  \item{\dots}{
116
other arguments to be passed to \code{\link{setClass}}.
117
}
118
}
119
 
61034 jmc 120
\value{
121
  \code{setRefClass()} returns a generator function suitable for
122
  creating objects from the class, invisibly.  A call to this function
123
  takes any number of arguments,
124
  which will be passed on to the initialize method.  If no
125
  \code{initialize} method is defined for the class or one of its
126
  superclasses, the default method expects named arguments with the
127
  name of one of the fields and unnamed arguments, if any, that are
128
  objects from one of the superclasses of this class (but only
129
  superclasses that are themselves reference classes have any effect).
130
 
131
  The generator function is similar to the S4 generator function
132
  returned by \code{\link{setClass}}. In addition to being a generator
133
  function, however, it is also a reference class generator object,
134
  with reference class methods for various utilities.  See the section
135
  on reference class generator objects below.
136
 
137
 
138
\code{getRefClass()} also returns the generator function for the
139
class.  Note that the package slot in the value is the correct package
140
from the class definition, regardless of  the \code{where} argument,
141
which is used only to
142
find the class if necessary.
143
}
144
 
145
 
52816 jmc 146
\section{Reference Objects}{
52903 jmc 147
Normal objects in \R are passed as arguments in function calls consistently with
52816 jmc 148
functional programming semantics; that is, changes made to an object
149
passed as an argument are local to the function call.  The object that
150
supplied the argument is unchanged.
151
 
62255 jmc 152
The functional model (sometimes called pass-by-value, although this is
153
inaccurate for \R) is
52903 jmc 154
suitable for many statistical computations and is implicit, for
52816 jmc 155
example, in the basic \R software for fitting statistical models.
52903 jmc 156
In some other situations, one would like all the code dealing with an
52816 jmc 157
object to see the exact same content, so that changes made in any
52903 jmc 158
computation would be reflected everywhere.
52816 jmc 159
This is often suitable if the object has some \dQuote{objective}
160
reality, such as a window in a user interface.
161
 
52903 jmc 162
In addition, commonly used languages, including Java, C++ and many
52816 jmc 163
others, support a version of classes and methods assuming reference
164
semantics.
53068 jmc 165
The corresponding programming mechanism
166
is to invoke a method on an object.
62255 jmc 167
In the \R syntax we use \code{"$"} %$
59654 jmc 168
for this operation; one invokes a method,
52816 jmc 169
\code{m1} say, on an object \code{x} by the expression
52903 jmc 170
\code{x$m1(...)}. %$
53068 jmc 171
 
172
Methods in this paradigm are associated with the object, or more
53003 jmc 173
precisely with the class of the object, as opposed to methods in a
174
function-based class/method system, which are fundamentally associated
175
with the function (in \R, for example, a generic function in an \R
176
session has a table of all its currently known methods).
177
In this document \dQuote{methods for a class} as opposed to
178
\dQuote{methods for a function} will make the distinction.
179
 
53068 jmc 180
Objects in this paradigm usually have named fields on which
52903 jmc 181
the methods operate.
53003 jmc 182
In the \R implementation, the fields are defined when the class is
183
created.
184
The field itself can optionally have a specified class, meaning that only objects
185
from this class or one of its subclasses can be assigned to the field.
186
By default, fields have class \code{"ANY"}.
187
 
53068 jmc 188
Fields are accessed by reference.
53003 jmc 189
In particular, invoking a method may modify the content of
52903 jmc 190
the fields.
52816 jmc 191
 
53003 jmc 192
Programming for such classes involves writing new methods for a
193
particular class.
53068 jmc 194
In the \R implementation, these methods are \R functions, with zero or
195
more formal arguments.
71540 jmc 196
For standard reference methods, the object itself is not an explicit
53003 jmc 197
argument to the method.
198
Instead, fields and methods for the class can be referred to by name
199
in the method definition.
71540 jmc 200
The implementation uses \R environments to make fields and other methods
201
available by name within the method.
202
Specifically, the parent environment of the method is the object itself.
203
  See the section on \dQuote{Writing
62255 jmc 204
  Reference Methods}.
71540 jmc 205
This special use of environments is optional.  If a method is defined
206
with an initial formal argument \code{.self}, that will be passed in
207
as the whole object, and the method follows the standard rules for any
208
function in a package.  See the section on \dQuote{External Methods}
53003 jmc 209
 
52816 jmc 210
The goal of the software described here is to provide a uniform
53068 jmc 211
programming style in \R for software dealing with reference classes, whether
212
implemented directly in \R or through an interface to one of the OOP
52816 jmc 213
languages.
53003 jmc 214
}
52816 jmc 215
 
52903 jmc 216
 
217
\section{Writing Reference Methods}{
53003 jmc 218
Reference methods are functions supplied as elements of a named list,
219
either
71540 jmc 220
when invoking \code{$methods()} %$}
53003 jmc 221
on a generator object \code{g} or as
222
the argument \code{methods} in a call to \code{setRefClass}.
71540 jmc 223
The two mechanisms have the same effect, but the first makes the code more readable.
224
 
225
Methods are written as ordinary \R functions but have some special
226
features and restrictions in their usual form.
227
In contrast to some other languages (e.g., Python), the object itself
228
does not need to be an argument in the method definition.
52903 jmc 229
The body of the function can contain calls to any other reference method,
53003 jmc 230
including those inherited from other reference classes and may refer
71540 jmc 231
to methods and to fields in the object by name.
52816 jmc 232
 
71540 jmc 233
Alternatively, a method may be an \emph{external} method.
234
This is signalled by \code{.self} being the first formal argument to the method.
235
The body of the method then works like any ordinary function.
68626 jmc 236
The methods are called like other methods (without the \code{.self}
237
argument, which is supplied internally and always refers to the object
238
itself).
71540 jmc 239
Inside the method, fields and other methods are accessed in the form
240
\code{.self$x}. %$
68627 jmc 241
External methods exist so that reference classes can inherit the
242
package environment of superclasses
71540 jmc 243
in other packages; see the section on \dQuote{External Methods}.
68626 jmc 244
 
53003 jmc 245
Fields may be modified in a method by using the
246
non-local assignment operator, \code{<<-}, as in the \code{$edit} and \code{$undo}
247
methods in the example below.
248
Note that non-local assignment is required:  a local assignment with
52816 jmc 249
the \code{<-} operator just creates a local object in the function
250
call, as it would in any \R function.
53275 jmc 251
When methods are installed, a heuristic check is made for local
252
assignments to field names and a warning issued if any are detected.
52816 jmc 253
 
52903 jmc 254
Reference methods should be kept simple; if they need to do some
255
specialized \R computation, that computation should use a separate \R
256
function that is called from the reference method.
52846 jmc 257
Specifically, methods can not use special features of the
53003 jmc 258
enclosing environment mechanism, since the method's environment is
259
used to access fields and other methods.
58004 jmc 260
In particular, methods should not use non-exported entries in the
261
package's namespace, because the methods may be inherited by a
262
reference class in another package.
263
 
71540 jmc 264
Two method names are interpreted specially, \code{initialize}
265
and \code{finalize}. If an \code{initialize} method is defined, it
266
will be invoked when an object is generated from the class.  See the
267
discussion of method \code{$new(...)} %$
268
in the section \dQuote{Initialization Methods}.
66540 jmc 269
 
71540 jmc 270
If a \code{finalize} method is defined, a function will be
271
\link[=reg.finalizer]{registered} to invoke it before the environment in
272
the object is discarded by the garbage collector; finalizers are
273
registered with \code{atexit=TRUE}, and so are also run at the end of
274
\R{} sessions. See the matrix viewer example for both initialize and
275
finalize methods.
276
 
52903 jmc 277
Reference methods can not themselves be generic functions; if you want
52856 jmc 278
additional function-based method dispatch, write a separate generic
52846 jmc 279
function and call that from the method.
52816 jmc 280
 
71540 jmc 281
Two special object names are available.
52846 jmc 282
The entire object can be referred to in a method by the reserved
71540 jmc 283
name \code{.self}.
284
The object \code{.refClassDef} contains the definition of the
53003 jmc 285
class of the object.
71540 jmc 286
These are accessed as fields but are read-only, with one exception.
62255 jmc 287
In principal, the \code{.self} field can be modified in the \code{$initialize} %$
55779 jmc 288
method, because the object is still being created at this stage.
71540 jmc 289
This is not recommended, as it can invalidate the object with respect
290
to its class.
52816 jmc 291
 
62255 jmc 292
 
53003 jmc 293
The methods available include methods inherited from superclasses, as
71540 jmc 294
discussed in the section \dQuote{Inheritance}.
53003 jmc 295
 
59654 jmc 296
Only methods actually used will be included in the environment
62255 jmc 297
corresponding to an individual object.  To declare that a method requires a
298
particular other method, the first method should include a call
59654 jmc 299
to \code{$usingMethods()} %$
300
with the name of the other method as an argument.
301
Declaring the methods this way is essential if the other method is used indirectly (e.g., via \code{\link{sapply}()}
302
or \code{\link{do.call}()}).
303
If it is called directly, code analysis will find it.
304
Declaring the method is harmless in any case, however, and may aid
305
readability of the source code.
306
 
53003 jmc 307
Documentation for the methods can be obtained by the \code{$help} %$}
308
method for the generator object.
53068 jmc 309
Methods for classes are not documented in the \code{Rd} format used
310
for \R functions.
311
Instead, the \code{$help} %$}
312
method prints the calling sequence of the method, followed by
313
self-documentation from the method definition, in the style of Python.
53003 jmc 314
If the first element of the body of the method is a literal character
53068 jmc 315
string (possibly multi-line), that string is interpreted as documentation.
316
See the method definitions in the example.
52816 jmc 317
}
71540 jmc 318
 
319
\section{Initialization Methods}{
320
If the class has a method defined for \code{$initialize()}, %$
321
this method will be called once the reference object has been
322
created.  You should write such a method for a class that needs to do
323
some special initialization.
324
In particular, a reference method is recommended rather than a method
325
for the S4 generic function \code{initialize()}, because some special initialization is
326
required for reference objects \emph{before} the initialization of
327
fields.
328
As with S4 classes, methods are written for \code{$initialize()} %$
329
and not for \code{$new()}, %$
330
both for the previous reason and also because \code{$new()} %$
331
is invoked on the generator object and would be a method for that class.
332
 
333
The default method for \code{$initialize()} %$
334
is equivalent to invoking the method \code{$initFields(...)}. %$
335
Named arguments assign initial values to the corresponding fields.
336
Unnamed arguments must be objects from this class or a reference
337
superclass of this class.
338
Fields will be initialized to the contents of the fields in such
339
objects, but named arguments override the corresponding inherited
340
fields.
341
Note that fields are simply assigned.  If the field is itself a
342
reference object, that object is not copied.
343
The new and previous object will share the reference.
344
Also, a field assigned from an unnamed argument counts as an
345
assignment for locked fields.
346
To override an inherited value for a locked field, the new value must
347
be one of the named arguments in the initializing call.
348
A later assignment of the field will result in an error.
349
 
350
Initialization methods need some care in design.
351
The generator
352
for a reference class will be called with no arguments, for example
353
when copying the object.
354
To ensure that these calls do not fail, the method must have defaults
355
for all arguments or check for \code{missing()}.
356
The method
357
should include \code{\dots} as an argument and
358
pass this on via \code{$callSuper()} (or \code{$initFields()} if
359
you know that your superclasses have no initialization methods).
360
This allows future class definitions that subclass this class, with
361
additional fields.
362
 
363
}
52816 jmc 364
\section{Inheritance}{
365
Reference classes inherit from other reference classes by using the
366
standard \R inheritance; that is, by including the superclasses in the
367
\code{contains=} argument when creating the new class.
368
The names of the reference superclasses are in slot
369
\code{refSuperClasses} of the class definition.
62255 jmc 370
Reference classes can inherit from ordinary S4 classes also, but this
371
is usually a bad idea if it mixes reference fields and non-reference slots.
372
See the comments in the section on \dQuote{Implementation}.
52816 jmc 373
 
53003 jmc 374
Class fields are inherited.  A class definition can override a field
375
of the same name in a superclass only if the overriding class is a
376
subclass of the class of the inherited field.  This ensures that a
377
valid object in the field remains valid for the superclass as well.
52816 jmc 378
 
52846 jmc 379
Inherited methods are installed in the same way as directly
52856 jmc 380
specified methods.
52846 jmc 381
The code in a method can refer to  inherited methods in the same
382
way as directly specified methods.
383
 
53003 jmc 384
A method may override a method of the same name in a superclass.
56985 maechler 385
The overriding method can call the superclass method by
53068 jmc 386
\code{callSuper(...)} as described below.
71540 jmc 387
}
53068 jmc 388
 
71540 jmc 389
\section{Methods Provided for all Objects}{
53068 jmc 390
 
71540 jmc 391
All reference classes inherit from the class \code{"envRefClass"}.
392
All reference objects can use the following methods.
393
 
53068 jmc 394
\describe{
395
\item{\code{$callSuper(...)}}{ %$
396
Calls the method inherited from a reference superclass.
397
The call is meaningful only from within another method, and will be
398
resolved to call the inherited method of the same name.
53003 jmc 399
The arguments to \code{$callSuper} %$}
400
are passed to the superclass version.
53068 jmc 401
See the matrix viewer class in the example.
402
 
53003 jmc 403
Note that the intended arguments for the superclass method must be
404
supplied explicitly; there is no convention for supplying the
405
arguments automatically, in contrast to the similar mechanism for
406
functional methods.
53068 jmc 407
}
52816 jmc 408
 
53669 jmc 409
\item{\code{$copy(shallow = FALSE)}}{ %$
410
Creates a copy of the object.  With reference classes, unlike ordinary
411
\R objects, merely assigning the object with a different name does not
412
create an independent copy.  If \code{shallow} is \code{FALSE}, any
413
field that is itself a reference object will also be copied, and
414
similarly recursively for its fields.  Otherwise, while reassigning a
415
field to a new reference object will have no side effect, modifying
416
such a field will still be reflected in both copies of the object.
417
The argument has no effect on non-reference objects in fields.  When
418
there are reference objects in some fields but it is asserted that
419
they will not be modified, using \code{shallow = TRUE} will save some
420
memory and time.
421
}
422
 
53696 jmc 423
\item{\code{$field(name, value)}}{ %$
424
With one argument, returns the field of the object with character
425
string \code{name}.  With two arguments, the corresponding field is
426
assigned \code{value}.  Assignment checks that \code{name} specifies a
427
valid field, but the single-argument version will attempt to get
428
anything of that name from the object's environment.
429
 
430
The \code{$field()} %$
431
method replaces the direct use of a field name, when the name of the
432
field must be calculated, or for looping over several fields.
433
}
434
 
56335 jmc 435
\item{\code{$export(Class)}}{ %$
436
Returns the result of coercing the object to \code{Class} (typically
437
one of the superclasses of the object's class).  Calling the method
438
has no side effect on the object itself.
439
}
440
 
53669 jmc 441
\item{\code{$getRefClass()}; \code{$getClass()}}{
442
These return respectively the generator object and the formal class
443
definition for the reference class of this object, efficiently.
444
}
445
 
446
 
447
 
53068 jmc 448
\item{\code{$import(value, Class = class(value))}}{ %$
449
Import the object \code{value} into the current object, replacing the
450
corresponding fields in the current object.
451
Object \code{value} must come from one of the superclasses of the
452
current object's class.
453
If argument \code{Class} is supplied, \code{value} is first coerced to
454
that class.
455
}
456
 
457
\item{\code{$initFields(...)}}{ %$
458
Initialize the fields of the object from the supplied arguments.  This
459
method is usually only called from a class with a \code{$initialize()}% $
460
method.  It corresponds to the default initialization for reference
461
classes.  If there are slots and non-reference superclasses, these may
462
be supplied in the \dots argument as well.
463
 
464
Typically, a specialized \code{$initialize()}% $
465
method carries out its own computations, then invokes \code{$initFields()}% $
466
to perform standard initialization, as shown in the
467
\code{matrixViewer} class in the example below.
468
}
55578 jmc 469
 
56335 jmc 470
\item{\code{$show()}}{ %$
471
This method is called when the object is printed automatically,
472
analogously to the \code{\link{show}} function.  A general method is
473
defined for class \code{"envRefClass"}.  User-defined reference
474
classes will often define their own method: see the Example below.
475
 
476
Note two points in the example.  As with any \code{show()} method, it
477
is a good idea to print the class explicitly to allow for subclasses
478
using the method.  Second, to call the \emph{function} \code{show()}
479
from the method, as opposed to the \code{$show()} %$
480
method itself, refer to \code{methods::show()} explicitly.
481
}
482
 
56985 maechler 483
\item{\code{$trace(what, ...)}, \code{$untrace(what)} }{
55578 jmc 484
Apply the tracing and debugging facilities of the \code{\link{trace}}
485
function to the reference method \code{what}.
486
 
487
All the arguments of the \code{\link{trace}}
488
function can be supplied, except for \code{signature}, which is not
489
meaningful.
490
 
491
The reference method can be invoked on either an object or the
492
generator for the class.  See the section on Debugging below for details.
493
}
59654 jmc 494
 
495
\item{\code{$usingMethods(...)}}{ %$
496
Reference methods used by this method are named as the arguments
497
 either quoted or unquoted.  In the code analysis phase of installing the
59660 hornik 498
 the present method, the declared methods will be included.  It is essential
59654 jmc 499
 to declare any methods used in a nonstandard way (e.g., via an apply function).
500
 Methods called directly do not need to be declared, but it is harmless to do so.
501
 \code{$usingMethods()} does nothing at run time. %$
502
}
53068 jmc 503
} % end describe
504
 
505
Objects also inherit two reserved fields:
506
\describe{
507
\item{\code{.self}}{
508
a reference to the entire object;
509
}
510
\item{\code{.refClassDef}}{
511
the class definition.
512
}
513
} % end \describe
514
The defined fields should not override these, and in general it is
515
unwise to define a field whose name begins with \code{"."}, since the
516
implementation may use such names for special purposes.
517
 
518
}
519
 
71540 jmc 520
\section{External Methods; Inter-Package Superclasses }{
68626 jmc 521
The environment of a method in a reference class is the object itself,
522
as an environment.
523
This allows the method to refer directly to fields and other methods,
524
without using the whole object and the \code{"$"} %$
525
operator.
526
The parent of that environment is the namespace of the package in
527
which the reference class is defined.
528
Computations in the method have access to all the objects in the
529
package's namespace, exported or not.
530
 
68627 jmc 531
When defining a class that contains a reference superclass in another
532
package, there is an ambiguity about which package namespace should
533
have that role.
534
The argument \code{inheritPackage} to \code{setRefClass()} controls
535
whether the environment of new objects should inherit from an
536
inherited class in another package or continue to inherit from the
537
current package's namespace.
68626 jmc 538
 
68627 jmc 539
If the superclass is \dQuote{lean}, with few methods, or exists
540
primarily to support a family of subclasses, then it may be better to
541
continue to use the new package's environment.
542
On the other hand, if the superclass was originally written as a
543
standalone, this choice may invalidate existing superclass methods.
544
For the superclass methods to continue to work, they must use only
545
exported functions in their package and the new package must import
546
these.
547
 
548
Either way, some methods may need to be written that do \emph{not}
549
assume the standard model for reference class methods, but behave
550
essentially as ordinary functions would in dealing with reference
551
class objects.
552
 
553
The mechanism is to recognize \emph{external methods}.
554
An external method  is
68626 jmc 555
written as a function in which the first argument, named \code{.self},
556
stands for the reference class object.
557
This function is supplied as the definition for a reference class method.
558
The method will be called, automatically, with the first argument
559
being the current object and the other arguments, if any, passed along
560
from the actual call.
561
 
562
Since an external method is an ordinary function in the source code
563
for its package, it has access to all the objects in the namespace.
564
Fields and methods in the reference class must be referred to in the
565
form \code{.self$name}.%$
566
 
567
If for some reason you do not want to use \code{.self} as the first
568
argument, a function \code{f()} can be converted explicitly as
569
\code{externalRefMethod(f)}, which returns an object of class
570
\code{"externalRefMethod"} that can be supplied as a method for the
571
class.
572
The first argument will still correspond to the whole object.
573
 
574
External methods can be supplied for any reference class, but there is no
575
obvious advantage unless they are needed.
576
They are more work to write, harder to read and (slightly) slower to
577
execute.
578
 
70158 jmc 579
\emph{NOTE:} If you are the author of a package whose reference
580
classes are likely to be subclassed in other packages, you can avoid
581
these questions entirely by writing methods that \emph{only} use
582
exported functions from your package, so that all the methods will
583
work from another package that imports yours.
584
 
68626 jmc 585
}
586
 
61034 jmc 587
\section{Reference Class Generators}{
53003 jmc 588
The call to \code{setRefClass} defines the specified class and
61034 jmc 589
returns a \dQuote{generator function} object for that class.
61058 jmc 590
This object has class \code{"refObjectGenerator"}; it inherits
61034 jmc 591
from \code{"function"} via \code{"classGeneratorFunction"} and can be
592
called to generate new objects from the reference class.
593
 
594
The returned object is also a reference class object, although not of
595
the standard construction.
596
It can be used to invoke reference methods and access fields in the usual way, but
597
instead of being implemented directly as an environment it has a
598
subsidiary generator object as a slot, a
599
standard reference object (of class
61058 jmc 600
\code{"refGeneratorSlot"}).
61034 jmc 601
Note that if one wanted to extend the reference class generator
602
capability with a subclass, this should be done by subclassing
61058 jmc 603
\code{"refGeneratorSlot"}, not \code{"refObjectGenerator"}.
61034 jmc 604
 
605
The fields are \code{def}, the class definition, and \code{className},
53003 jmc 606
the character string name of the class.
61034 jmc 607
Methods generate objects
53003 jmc 608
from the class, to access help on reference methods, and to
609
define new reference methods for the class.
610
The currently available methods are:
52903 jmc 611
\describe{
612
\item{\code{$new(...)}}{ %$
61034 jmc 613
This method is equivalent to calling the generator function returned
614
by \code{setRefClass}.
52903 jmc 615
}
53470 jmc 616
 
52903 jmc 617
\item{\code{$help(topic)}}{ %$
618
Prints brief help on the topic.  The topics recognized
619
are reference method names, quoted or not.
620
 
621
The information printed is the calling sequence for the method, plus
622
self-documentation if any.
623
Reference methods can have an initial character string or vector as
624
the first element in the body of the function defining the method.
625
If so, this string is taken as self-documentation for the method (see
53068 jmc 626
the section on \dQuote{Writing Reference Methods} for details).
52903 jmc 627
 
628
If no topic is given or if the topic is not a method name, the
629
definition of the class is printed.
630
}
631
\item{\code{$methods(...)}}{ %$
68626 jmc 632
With no arguments, returns the names of the reference methods for this
53003 jmc 633
class.
68626 jmc 634
With one character string argument, returns the method of that name.
53003 jmc 635
 
636
Named arguments
637
are method definitions, which will be
52903 jmc 638
installed in the class, as if they had been supplied in the
53003 jmc 639
\code{methods} argument to \code{setRefClass()}.
55988 jmc 640
Supplying methods in this way, rather than in the call to
68626 jmc 641
\code{setRefClass()}, is recommended for the sake of clearer source
642
code.
643
See the section on \dQuote{Writing Reference Methods} for details.
644
 
55988 jmc 645
All methods for a class should be defined in the source code that
646
defines the class, typically as part of a package.
647
In particular, methods can not be redefined in a class in an attached
648
package with a namespace: The class method checks for a locked
649
binding of the class definition.
52903 jmc 650
 
55988 jmc 651
 
52903 jmc 652
The new methods can refer to any currently defined method by name
653
(including other methods supplied in this call to
74363 maechler 654
\code{$methods()}). %$
52903 jmc 655
Note though that previously defined methods are not re-analyzed
656
meaning that they will not call the new method (unless it redefines an
657
existing method of the same name).
658
 
659
To remove a method, supply \code{NULL} as its new definition.
660
}
53003 jmc 661
 
662
\item{\code{$fields()}}{ %$}{
663
Returns a list of the fields, each with its corresponding class.
664
Fields for which an accessor function was supplied in the definition
665
have class \code{"activeBindingFunction"}.
52903 jmc 666
}
53003 jmc 667
 
668
\item{\code{$lock(...)}}{ %$}{
669
The fields named in the arguments are locked; specifically, after the
670
lock method is called, the field may be set once.  Any further attempt
671
to set it will generate an error.
672
 
57589 jmc 673
If called with no arguments, the method returns the names of the
674
locked fields.
675
 
53003 jmc 676
Fields that are defined by an explicit accessor function can not be
677
locked (on the other hand, the accessor function can be defined to
678
generate an error if called with an argument).
55988 jmc 679
 
680
All code to lock fields should normally be part of the definition of a
681
class; that is, the read-only nature of the fields is meant to be part
682
of the class definition, not a dynamic property added later.
683
In particular, fields can not be locked in a class in an attached
684
package with a namespace:  The class method checks for a locked
57589 jmc 685
binding of the class definition.  Locked fields can not be
686
subsequently unlocked.
52903 jmc 687
}
688
 
55578 jmc 689
\item{\code{$trace(what, ..., classMethod = FALSE)}}{ %$}{
690
Establish a traced version of method \code{what} for objects generated
691
from this class.  The generator object tracing works like the
692
\code{$trace()}%$
693
method for objects from the class, with two differences.
694
Since it changes the method definition in the class object itself,
695
tracing applies to all objects, not just the one on which the trace
696
method is invoked.
697
 
698
Second, the optional argument \code{classMethod = TRUE} allows tracing
61034 jmc 699
on the methods of the generator object itself.
55578 jmc 700
By default, \code{what} is interpreted as the name of a method in the
701
class for which this object is the generator.
702
}
703
 
53003 jmc 704
\item{\code{$accessors(...)}}{ %$}{
705
A number of
706
systems using the OOP programming paradigm recommend or enforce
707
\emph{getter and setter methods}
708
corresponding to each field, rather than direct access by name.
62255 jmc 709
If you like this style and want to  extract a field named \code{abc}
710
by \code{x$getAbc()} and assign it by
711
\code{x$setAbc(value)},
712
the \code{$accessors} %$}
713
method is a convenience function that creates such getter and setter methods for the
53003 jmc 714
specified fields.
62255 jmc 715
Otherwise there is no reason to use this mechanism.  In particular, it
716
has nothing to do with the general ability to define fields by
717
functions as described in the section on \dQuote{Reference Objects}.
53003 jmc 718
}
719
} %% end of \describe
720
} %% end of \section
721
 
72016 hornik 722
\section{Implementation; Reference Classes as S4 Classes}{
53003 jmc 723
Reference classes are implemented as S4 classes with a data part of
724
type \code{"environment"}.
725
Fields correspond to named objects in the environment.
62255 jmc 726
A field associated with a function is implemented as an
53003 jmc 727
\link[=bindenv]{active binding}.
62255 jmc 728
In particular, fields with a specified class are implemented as a
53003 jmc 729
special form of active binding to enforce valid assignment to the
730
field.
71540 jmc 731
 
732
As a related feature,  the element in the \code{fields=} list supplied
733
to \code{setRefClass} can be an \emph{accessor
734
   function}, a function of one argument that returns
735
the field if called with no argument or sets it to the value of the
736
argument otherwise.
737
Accessor functions are used internally and for inter-system interface
738
applications, but not generally recommended as they blur the concept
739
of fields as data within the object.
740
 
53003 jmc 741
A field, say \code{data}, can be accessed generally by an expression
742
of the form \code{x$data} %$}
743
for any object from the relevant class.
72015 jmc 744
In an internal method for this class, the field can be accessed by the name
53003 jmc 745
\code{data}.
746
A field that is not locked can be set by an expression of the form
747
\code{x$data <- value}.%$
72015 jmc 748
Inside an internal method, a field can be assigned by an expression of the form
53003 jmc 749
\code{x <<- value}.
750
Note the \link[=assignOps]{non-local assignment} operator.
751
The standard \R interpretation of this operator works to assign it in
752
the environment of the object.
53068 jmc 753
If the field has an accessor function defined, getting and setting
754
will call that function.
53003 jmc 755
 
53068 jmc 756
When a method is invoked on an object, the function defining the method is
757
installed in the object's environment, with the same environment as the
53003 jmc 758
environment of the function.
53068 jmc 759
 
72015 jmc 760
Reference classes can have validity methods in the same sense as any
761
S4 class (see \code{\link{setValidity}}).
762
Such methods are often a good idea; they will be called by calling
763
\code{\link{validObject}} and a validity method, if one is defined,
764
will be called when a reference object is created (from version 3.4 of
765
\R on).
766
Just remember that these are S4 methods.  The function will be called
767
with the \code{object} as its argument.  Fields and methods must be
768
accessed using \code{$}.%$
769
 
71540 jmc 770
\emph{Note: Slots.} Because of the implementation, new reference classes can inherit from
771
non-reference S4 classes as well as reference classes, and can include
772
class-specific slots in the definition.
62255 jmc 773
This is usually a bad idea, if the slots from the non-reference
774
class are thought of as alternatives to fields.
71540 jmc 775
Slots will as always be treated functionally.
776
Therefore, changes to the slots and the fields will behave inconsistently,
777
mixing the functional
778
and reference paradigms for properties of the same object,
779
conceptually unclear and prone to errors.
62255 jmc 780
In addition, the initialization method for the class will have to sort
781
out fields from slots, with a good chance of creating anomalous
782
behavior for subclasses of this class.
783
 
71540 jmc 784
Inheriting from a \link[=setClassUnion]{class union}, however, is a reasonable strategy (with
785
all members of the union likely to be reference classes).
53003 jmc 786
 
52856 jmc 787
}
52816 jmc 788
 
789
 
55578 jmc 790
\section{Debugging}{
791
The standard \R{} debugging and tracing facilities can be applied to
792
reference methods.
793
Reference methods can be passed to \code{\link{debug}} and its
794
relatives from an object to debug further method invocations on that
795
object; for example, \code{debug(xx$edit)}. %$
796
 
797
Somewhat more flexible use is available for a reference method version
798
of the \code{\link{trace}} function.
799
A corresponding \code{$trace()} %$
800
reference method is available for
801
either an object or for the reference class generator
56335 jmc 802
(\code{xx$trace()} or \code{mEdit$trace()} in the example below).
55578 jmc 803
Using \code{$trace()} on an object sets up a tracing
804
version for future invocations of the specified method for that
805
object.
806
Using \code{$trace()} on the generator for the class sets up a
62255 jmc 807
tracing version for all future objects from that class (and sometimes for
808
existing objects from the class if the method is not declared or
809
previously invoked).
55578 jmc 810
 
811
In either case, all the arguments to the standard  \code{\link{trace}}
812
function are available, except for \code{signature=} which is
813
meaningless since reference methods can not be S4 generic functions.
814
This includes the typical style \code{trace(what, browser)} for
815
interactive debugging and  \code{trace(what, edit = TRUE)} to edit the
816
reference method interactively.
817
 
52903 jmc 818
}
71540 jmc 819
 
71366 jmc 820
\references{
821
 Chambers, John M. (2016)
822
 \emph{Extending R},
823
  Chapman & Hall.
824
(Chapters 9 and 11.)
52816 jmc 825
}
826
 
71366 jmc 827
 
56985 maechler 828
\examples{
53003 jmc 829
## a simple editor for matrix objects.  Method  $edit() changes some
830
## range of values; method $undo() undoes the last edit.
56335 jmc 831
mEdit <- setRefClass("mEdit",
52960 jmc 832
      fields = list( data = "matrix",
71540 jmc 833
        edits = "list"))
834
 
835
## The basic edit, undo methods
836
mEdit$methods(
52816 jmc 837
     edit = function(i, j, value) {
53003 jmc 838
       ## the following string documents the edit method
839
       'Replaces the range [i, j] of the
840
        object by value.
841
        '
52816 jmc 842
         backup <-
843
             list(i, j, data[i,j])
53003 jmc 844
         data[i,j] <<- value
54337 jmc 845
         edits <<- c(edits, list(backup))
52816 jmc 846
         invisible(value)
847
     },
848
     undo = function() {
53003 jmc 849
       'Undoes the last edit() operation
850
        and update the edits field accordingly.
851
        '
52960 jmc 852
         prev <- edits
54337 jmc 853
         if(length(prev)) prev <- prev[[length(prev)]]
52816 jmc 854
         else stop("No more edits to undo")
855
         edit(prev[[1]], prev[[2]], prev[[3]])
856
         ## trim the edits list
857
         length(edits) <<- length(edits) - 2
858
         invisible(prev)
71540 jmc 859
     })
860
 
861
## A method to automatically print objects
862
mEdit$methods(
56335 jmc 863
     show = function() {
864
       'Method for automatically printing matrix editors'
865
       cat("Reference matrix editor object of class",
866
          classLabel(class(.self)), "\n")
867
       cat("Data: \n")
868
       methods::show(data)
869
       cat("Undo list is of length", length(edits), "\n")
52816 jmc 870
     }
71540 jmc 871
     )
56985 maechler 872
 
52960 jmc 873
xMat <- matrix(1:12,4,3)
61034 jmc 874
xx <- mEdit(data = xMat)
52960 jmc 875
xx$edit(2, 2, 0)
56335 jmc 876
xx
52960 jmc 877
xx$undo()
56335 jmc 878
mEdit$help("undo")
52960 jmc 879
stopifnot(all.equal(xx$data, xMat))
53003 jmc 880
 
71540 jmc 881
utils::str(xx) # show fields and names of methods
56985 maechler 882
 
71540 jmc 883
## A method to save the object
56335 jmc 884
mEdit$methods(
53003 jmc 885
     save = function(file) {
886
       'Save the current object on the file
887
        in R external object format.
888
       '
889
         base::save(.self, file = file)
890
     }
56985 maechler 891
)
53003 jmc 892
 
52960 jmc 893
tf <- tempfile()
56335 jmc 894
xx$save(tf)
53003 jmc 895
\dontshow{
52960 jmc 896
load(tf)
897
unlink(tf)
898
stopifnot(identical(xx$data, .self$data))
899
}
52816 jmc 900
 
53068 jmc 901
\dontrun{
52816 jmc 902
## Inheriting a reference class:  a matrix viewer
56985 maechler 903
mv <- setRefClass("matrixViewer",
53068 jmc 904
    fields = c("viewerDevice", "viewerFile"),
56335 jmc 905
    contains = "mEdit",
53068 jmc 906
    methods = list( view = function() {
907
        dd <- dev.cur(); dev.set(viewerDevice)
908
        devAskNewPage(FALSE)
909
        matplot(data, main = paste("After",length(edits),"edits"))
910
        dev.set(dd)},
52816 jmc 911
        edit = # invoke previous method, then replot
912
          function(i, j, value) {
52903 jmc 913
            callSuper(i, j, value)
52816 jmc 914
            view()
915
          }))
916
 
53068 jmc 917
## initialize and finalize methods
56985 maechler 918
mv$methods( initialize =
53470 jmc 919
  function(file = "./matrixView.pdf", ...) {
920
    viewerFile <<- file
53068 jmc 921
    pdf(viewerFile)
922
    viewerDevice <<- dev.cur()
923
    dev.set(dev.prev())
53470 jmc 924
    callSuper(...)
53068 jmc 925
  },
926
  finalize = function() {
927
    dev.off(viewerDevice)
928
  })
55578 jmc 929
 
930
## debugging an object: call browser() in method $edit()
931
xx$trace(edit, browser)
932
 
56335 jmc 933
## debugging all objects from class mEdit in method $undo()
934
mEdit$trace(undo, browser)
53068 jmc 935
}
52816 jmc 936
\dontshow{
56335 jmc 937
removeClass("mEdit")
53068 jmc 938
resetGeneric("$")
939
resetGeneric("initialize")
940
} %$
52816 jmc 941
}
942
\keyword{ programming }
943
\keyword{ classes }