Rev 81629 | Blame | Compare with Previous | Last modification | View Log | Download | RSS feed
% File src/library/methods/man/refClass.Rd% Part of the R package, https://www.R-project.org% Copyright 2010-2014 R Core Team% Distributed under GPL 2 or later\name{ReferenceClasses}\title{Objects With Fields Treated by Reference (OOP-style)}\alias{ReferenceClasses}\alias{setRefClass}\alias{getRefClass}\alias{initFieldArgs}\alias{initRefFields}\alias{activeBindingFunction-class}\alias{defaultBindingFunction-class}\alias{uninitializedField-class}\alias{refClassRepresentation-class}\alias{refObjectGenerator-class}\alias{refGeneratorSlot-class}\alias{refClass-class}\alias{refObject-class}\alias{refMethodDef-class}\alias{refMethodDefWithTrace-class}\alias{SuperClassMethod-class}\alias{show,envRefClass-method}\alias{show,refMethodDef-method}\alias{show,externalRefMethod-method}\alias{show,refClassRepresentation-method}\alias{externalRefMethod}\alias{externalRefMethod-class}\description{The software described here allows packages to define \emph{referenceclasses} that behave in the style of \dQuote{OOP} languages such as Java andC++.This model for OOP differs from the functional model implemented by S4(and S3) classes and methods, in which methods are defined for genericfunctions.Methods for reference classes are \dQuote{encapsulated} in the class definition.Computations with objects from reference classes invoke methods on them andextract or set their fields, using the \code{`$`} operator in \R.%$The field and method computations potentially modify the object.All computations referring to the objects see the modifications, in contrast tothe usual functional programming model in \R.A call to\code{setRefClass} in the source code for a package defines the class and returns a generator object.Subsequent calls to the \code{$methods()} %$method of the generator will define methods for the class.As with functional classes, if the class is exported from the package,it will be available when the package is loaded.Methods are \R functions. In their usual implementation, they refer to fieldsand other methods of the class directly by name. See the section on\dQuote{Writing Reference Methods}.As with functional classes, reference classes can inherit from otherreference classes via a \code{contains=} argument to\code{setRefClass}. Fields and methods will be inherited, except where thenew class overrides method definitions. See the section on \dQuote{Inheritance}.}\usage{setRefClass(Class, fields = , contains = , methods =,where =, inheritPackage =, ...)getRefClass(Class, where =)}\arguments{\item{Class}{character string name for the class.In the call to \code{getRefClass()} this argument can also be anyobject from the relevant class.}\item{fields}{either a character vector of field names ora named list of the fields. The resulting fields will be accessed with reference semantics (seethe section on \dQuote{Reference Objects}). If the argument is a list, eachelement of the list should usually be the character string name of a class, inwhich case the object in the field must be from that class or asubclass. An alternative, but not generally recommended, is to supply an \emph{accessorfunction}; see the section on \dQuote{Implementation} for accessorfunctions and the related internal mechanism.Note that fields are distinct fromslots. Reference classes should not define class-specific slots. Seethe note on slots in the\dQuote{Implementation} section.}\item{contains}{optional vector of superclasses for this class. If a superclass isalso a reference class, the fields and class-based methods will be inherited.}\item{methods}{a named list of function definitions that can be invoked on objectsfrom this class. These can also be created by invoking the\code{$methods} method on the generator object returned. %$See the section on \dQuote{Writing Reference Methods} for details.}\item{where}{for \code{setRefClass}, the environment in which to store the class definition. Should beomitted in calls from a package's source code.For \code{getRefClass}, the environment from which to search for the definition. If thepackage is not loaded or you need to be specific, use\code{\link{asNamespace}} with the package name.}\item{inheritPackage}{Should objects from the new class inherit the package environment of acontained superclass? Default \code{FALSE}. See the Section \dQuote{Inter-Package Superclassesand External Methods}.}\item{\dots}{other arguments to be passed to \code{\link{setClass}}.}}\value{\code{setRefClass()} returns a generator function suitable forcreating objects from the class, invisibly. A call to this functiontakes any number of arguments,which will be passed on to the initialize method. If no\code{initialize} method is defined for the class or one of itssuperclasses, the default method expects named arguments with thename of one of the fields and unnamed arguments, if any, that areobjects from one of the superclasses of this class (but onlysuperclasses that are themselves reference classes have any effect).The generator function is similar to the S4 generator functionreturned by \code{\link{setClass}}. In addition to being a generatorfunction, however, it is also a reference class generator object,with reference class methods for various utilities. See the sectionon reference class generator objects below.\code{getRefClass()} also returns the generator function for theclass. Note that the package slot in the value is the correct packagefrom the class definition, regardless of the \code{where} argument,which is used only tofind the class if necessary.}\section{Reference Objects}{Normal objects in \R are passed as arguments in function calls consistently withfunctional programming semantics; that is, changes made to an objectpassed as an argument are local to the function call. The object thatsupplied the argument is unchanged.The functional model (sometimes called pass-by-value, although this isinaccurate for \R) issuitable for many statistical computations and is implicit, forexample, in the basic \R software for fitting statistical models.In some other situations, one would like all the code dealing with anobject to see the exact same content, so that changes made in anycomputation would be reflected everywhere.This is often suitable if the object has some \dQuote{objective}reality, such as a window in a user interface.In addition, commonly used languages, including Java, C++ and manyothers, support a version of classes and methods assuming referencesemantics.The corresponding programming mechanismis to invoke a method on an object.In the \R syntax we use \code{"$"} %$for this operation; one invokes a method,\code{m1} say, on an object \code{x} by the expression\code{x$m1(...)}. %$Methods in this paradigm are associated with the object, or moreprecisely with the class of the object, as opposed to methods in afunction-based class/method system, which are fundamentally associatedwith the function (in \R, for example, a generic function in an \Rsession has a table of all its currently known methods).In this document \dQuote{methods for a class} as opposed to\dQuote{methods for a function} will make the distinction.Objects in this paradigm usually have named fields on whichthe methods operate.In the \R implementation, the fields are defined when the class iscreated.The field itself can optionally have a specified class, meaning that only objectsfrom this class or one of its subclasses can be assigned to the field.By default, fields have class \code{"ANY"}.Fields are accessed by reference.In particular, invoking a method may modify the content ofthe fields.Programming for such classes involves writing new methods for aparticular class.In the \R implementation, these methods are \R functions, with zero ormore formal arguments.For standard reference methods, the object itself is not an explicitargument to the method.Instead, fields and methods for the class can be referred to by namein the method definition.The implementation uses \R environments to make fields and other methodsavailable by name within the method.Specifically, the parent environment of the method is the object itself.See the section on \dQuote{WritingReference Methods}.This special use of environments is optional. If a method is definedwith an initial formal argument \code{.self}, that will be passed inas the whole object, and the method follows the standard rules for anyfunction in a package. See the section on \dQuote{External Methods}The goal of the software described here is to provide a uniformprogramming style in \R for software dealing with reference classes, whetherimplemented directly in \R or through an interface to one of the OOPlanguages.}\section{Writing Reference Methods}{Reference methods are functions supplied as elements of a named list,eitherwhen invoking \code{$methods()} %$}on a generator object \code{g} or asthe argument \code{methods} in a call to \code{setRefClass}.The two mechanisms have the same effect, but the first makes the code more readable.Methods are written as ordinary \R functions but have some specialfeatures and restrictions in their usual form.In contrast to some other languages (e.g., Python), the object itselfdoes not need to be an argument in the method definition.The body of the function can contain calls to any other reference method,including those inherited from other reference classes and may referto methods and to fields in the object by name.Alternatively, a method may be an \emph{external} method.This is signalled by \code{.self} being the first formal argument to the method.The body of the method then works like any ordinary function.The methods are called like other methods (without the \code{.self}argument, which is supplied internally and always refers to the objectitself).Inside the method, fields and other methods are accessed in the form\code{.self$x}. %$External methods exist so that reference classes can inherit thepackage environment of superclassesin other packages; see the section on \dQuote{External Methods}.Fields may be modified in a method by using thenon-local assignment operator, \code{<<-}, as in the \code{$edit} and \code{$undo}methods in the example below.Note that non-local assignment is required: a local assignment withthe \code{<-} operator just creates a local object in the functioncall, as it would in any \R function.When methods are installed, a heuristic check is made for localassignments to field names and a warning issued if any are detected.Reference methods should be kept simple; if they need to do somespecialized \R computation, that computation should use a separate \Rfunction that is called from the reference method.Specifically, methods can not use special features of theenclosing environment mechanism, since the method's environment isused to access fields and other methods.In particular, methods should not use non-exported entries in thepackage's namespace, because the methods may be inherited by areference class in another package.Two method names are interpreted specially, \code{initialize}and \code{finalize}. If an \code{initialize} method is defined, itwill be invoked when an object is generated from the class. See thediscussion of method \code{$new(...)} %$in the section \dQuote{Initialization Methods}.If a \code{finalize} method is defined, a function will be\link[=reg.finalizer]{registered} to invoke it before the environment inthe object is discarded by the garbage collector; finalizers areregistered with \code{atexit=TRUE}, and so are also run at the end of\R{} sessions. See the matrix viewer example for both initialize andfinalize methods.Reference methods can not themselves be generic functions; if you wantadditional function-based method dispatch, write a separate genericfunction and call that from the method.Two special object names are available.The entire object can be referred to in a method by the reservedname \code{.self}.The object \code{.refClassDef} contains the definition of theclass of the object.These are accessed as fields but are read-only, with one exception.In principal, the \code{.self} field can be modified in the \code{$initialize} %$method, because the object is still being created at this stage.This is not recommended, as it can invalidate the object with respectto its class.The methods available include methods inherited from superclasses, asdiscussed in the section \dQuote{Inheritance}.Only methods actually used will be included in the environmentcorresponding to an individual object. To declare that a method requires aparticular other method, the first method should include a callto \code{$usingMethods()} %$with the name of the other method as an argument.Declaring the methods this way is essential if the other method is used indirectly (e.g., via \code{\link{sapply}()}or \code{\link{do.call}()}).If it is called directly, code analysis will find it.Declaring the method is harmless in any case, however, and may aidreadability of the source code.Documentation for the methods can be obtained by the \code{$help} %$}method for the generator object.Methods for classes are not documented in the \code{Rd} format usedfor \R functions.Instead, the \code{$help} %$}method prints the calling sequence of the method, followed byself-documentation from the method definition, in the style of Python.If the first element of the body of the method is a literal characterstring (possibly multi-line), that string is interpreted as documentation.See the method definitions in the example.}\section{Initialization Methods}{If the class has a method defined for \code{$initialize()}, %$this method will be called once the reference object has beencreated. You should write such a method for a class that needs to dosome special initialization.In particular, a reference method is recommended rather than a methodfor the S4 generic function \code{initialize()}, because some special initialization isrequired for reference objects \emph{before} the initialization offields.As with S4 classes, methods are written for \code{$initialize()} %$and not for \code{$new()}, %$both for the previous reason and also because \code{$new()} %$is invoked on the generator object and would be a method for that class.The default method for \code{$initialize()} %$is equivalent to invoking the method \code{$initFields(...)}. %$Named arguments assign initial values to the corresponding fields.Unnamed arguments must be objects from this class or a referencesuperclass of this class.Fields will be initialized to the contents of the fields in suchobjects, but named arguments override the corresponding inheritedfields.Note that fields are simply assigned. If the field is itself areference object, that object is not copied.The new and previous object will share the reference.Also, a field assigned from an unnamed argument counts as anassignment for locked fields.To override an inherited value for a locked field, the new value mustbe one of the named arguments in the initializing call.A later assignment of the field will result in an error.Initialization methods need some care in design.The generatorfor a reference class will be called with no arguments, for examplewhen copying the object.To ensure that these calls do not fail, the method must have defaultsfor all arguments or check for \code{missing()}.The methodshould include \code{\dots} as an argument andpass this on via \code{$callSuper()} (or \code{$initFields()} ifyou know that your superclasses have no initialization methods).This allows future class definitions that subclass this class, withadditional fields.}\section{Inheritance}{Reference classes inherit from other reference classes by using thestandard \R inheritance; that is, by including the superclasses in the\code{contains=} argument when creating the new class.The names of the reference superclasses are in slot\code{refSuperClasses} of the class definition.Reference classes can inherit from ordinary S4 classes also, but thisis usually a bad idea if it mixes reference fields and non-reference slots.See the comments in the section on \dQuote{Implementation}.Class fields are inherited. A class definition can override a fieldof the same name in a superclass only if the overriding class is asubclass of the class of the inherited field. This ensures that avalid object in the field remains valid for the superclass as well.Inherited methods are installed in the same way as directlyspecified methods.The code in a method can refer to inherited methods in the sameway as directly specified methods.A method may override a method of the same name in a superclass.The overriding method can call the superclass method by\code{callSuper(...)} as described below.}\section{Methods Provided for all Objects}{All reference classes inherit from the class \code{"envRefClass"}.All reference objects can use the following methods.\describe{\item{\code{$callSuper(...)}}{ %$Calls the method inherited from a reference superclass.The call is meaningful only from within another method, and will beresolved to call the inherited method of the same name.The arguments to \code{$callSuper} %$}are passed to the superclass version.See the matrix viewer class in the example.Note that the intended arguments for the superclass method must besupplied explicitly; there is no convention for supplying thearguments automatically, in contrast to the similar mechanism forfunctional methods.}\item{\code{$copy(shallow = FALSE)}}{ %$Creates a copy of the object. With reference classes, unlike ordinary\R objects, merely assigning the object with a different name does notcreate an independent copy. If \code{shallow} is \code{FALSE}, anyfield that is itself a reference object will also be copied, andsimilarly recursively for its fields. Otherwise, while reassigning afield to a new reference object will have no side effect, modifyingsuch a field will still be reflected in both copies of the object.The argument has no effect on non-reference objects in fields. Whenthere are reference objects in some fields but it is asserted thatthey will not be modified, using \code{shallow = TRUE} will save somememory and time.}\item{\code{$field(name, value)}}{ %$With one argument, returns the field of the object with characterstring \code{name}. With two arguments, the corresponding field isassigned \code{value}. Assignment checks that \code{name} specifies avalid field, but the single-argument version will attempt to getanything of that name from the object's environment.The \code{$field()} %$method replaces the direct use of a field name, when the name of thefield must be calculated, or for looping over several fields.}\item{\code{$export(Class)}}{ %$Returns the result of coercing the object to \code{Class} (typicallyone of the superclasses of the object's class). Calling the methodhas no side effect on the object itself.}\item{\code{$getRefClass()}; \code{$getClass()}}{These return respectively the generator object and the formal classdefinition for the reference class of this object, efficiently.}\item{\code{$import(value, Class = class(value))}}{ %$Import the object \code{value} into the current object, replacing thecorresponding fields in the current object.Object \code{value} must come from one of the superclasses of thecurrent object's class.If argument \code{Class} is supplied, \code{value} is first coerced tothat class.}\item{\code{$initFields(...)}}{ %$Initialize the fields of the object from the supplied arguments. Thismethod is usually only called from a class with a \code{$initialize()}% $method. It corresponds to the default initialization for referenceclasses. If there are slots and non-reference superclasses, these maybe supplied in the \dots argument as well.Typically, a specialized \code{$initialize()}% $method carries out its own computations, then invokes \code{$initFields()}% $to perform standard initialization, as shown in the\code{matrixViewer} class in the example below.}\item{\code{$show()}}{ %$This method is called when the object is printed automatically,analogously to the \code{\link{show}} function. A general method isdefined for class \code{"envRefClass"}. User-defined referenceclasses will often define their own method: see the Example below.Note two points in the example. As with any \code{show()} method, itis a good idea to print the class explicitly to allow for subclassesusing the method. Second, to call the \emph{function} \code{show()}from the method, as opposed to the \code{$show()} %$method itself, refer to \code{methods::show()} explicitly.}\item{\code{$trace(what, ...)}, \code{$untrace(what)} }{Apply the tracing and debugging facilities of the \code{\link{trace}}function to the reference method \code{what}.All the arguments of the \code{\link{trace}}function can be supplied, except for \code{signature}, which is notmeaningful.The reference method can be invoked on either an object or thegenerator for the class. See the section on Debugging below for details.}\item{\code{$usingMethods(...)}}{ %$Reference methods used by this method are named as the argumentseither quoted or unquoted. In the code analysis phase of installingthe present method, the declared methods will be included. It is essentialto declare any methods used in a nonstandard way (e.g., via an apply function).Methods called directly do not need to be declared, but it is harmless to do so.\code{$usingMethods()} does nothing at run time. %$}} % end describeObjects also inherit two reserved fields:\describe{\item{\code{.self}}{a reference to the entire object;}\item{\code{.refClassDef}}{the class definition.}} % end \describeThe defined fields should not override these, and in general it isunwise to define a field whose name begins with \code{"."}, since theimplementation may use such names for special purposes.}\section{External Methods; Inter-Package Superclasses }{The environment of a method in a reference class is the object itself,as an environment.This allows the method to refer directly to fields and other methods,without using the whole object and the \code{"$"} %$operator.The parent of that environment is the namespace of the package inwhich the reference class is defined.Computations in the method have access to all the objects in thepackage's namespace, exported or not.When defining a class that contains a reference superclass in anotherpackage, there is an ambiguity about which package namespace shouldhave that role.The argument \code{inheritPackage} to \code{setRefClass()} controlswhether the environment of new objects should inherit from aninherited class in another package or continue to inherit from thecurrent package's namespace.If the superclass is \dQuote{lean}, with few methods, or existsprimarily to support a family of subclasses, then it may be better tocontinue to use the new package's environment.On the other hand, if the superclass was originally written as astandalone, this choice may invalidate existing superclass methods.For the superclass methods to continue to work, they must use onlyexported functions in their package and the new package must importthese.Either way, some methods may need to be written that do \emph{not}assume the standard model for reference class methods, but behaveessentially as ordinary functions would in dealing with referenceclass objects.The mechanism is to recognize \emph{external methods}.An external method iswritten as a function in which the first argument, named \code{.self},stands for the reference class object.This function is supplied as the definition for a reference class method.The method will be called, automatically, with the first argumentbeing the current object and the other arguments, if any, passed alongfrom the actual call.Since an external method is an ordinary function in the source codefor its package, it has access to all the objects in the namespace.Fields and methods in the reference class must be referred to in theform \code{.self$name}.%$If for some reason you do not want to use \code{.self} as the firstargument, a function \code{f()} can be converted explicitly as\code{externalRefMethod(f)}, which returns an object of class\code{"externalRefMethod"} that can be supplied as a method for theclass.The first argument will still correspond to the whole object.External methods can be supplied for any reference class, but there is noobvious advantage unless they are needed.They are more work to write, harder to read and (slightly) slower toexecute.\emph{NOTE:} If you are the author of a package whose referenceclasses are likely to be subclassed in other packages, you can avoidthese questions entirely by writing methods that \emph{only} useexported functions from your package, so that all the methods willwork from another package that imports yours.}\section{Reference Class Generators}{The call to \code{setRefClass} defines the specified class andreturns a \dQuote{generator function} object for that class.This object has class \code{"refObjectGenerator"}; it inheritsfrom \code{"function"} via \code{"classGeneratorFunction"} and can becalled to generate new objects from the reference class.The returned object is also a reference class object, although not ofthe standard construction.It can be used to invoke reference methods and access fields in the usual way, butinstead of being implemented directly as an environment it has asubsidiary generator object as a slot, astandard reference object (of class\code{"refGeneratorSlot"}).Note that if one wanted to extend the reference class generatorcapability with a subclass, this should be done by subclassing\code{"refGeneratorSlot"}, not \code{"refObjectGenerator"}.The fields are \code{def}, the class definition, and \code{className},the character string name of the class.Methods generate objectsfrom the class, to access help on reference methods, and todefine new reference methods for the class.The currently available methods are:\describe{\item{\code{$new(...)}}{ %$This method is equivalent to calling the generator function returnedby \code{setRefClass}.}\item{\code{$help(topic)}}{ %$Prints brief help on the topic. The topics recognizedare reference method names, quoted or not.The information printed is the calling sequence for the method, plusself-documentation if any.Reference methods can have an initial character string or vector asthe first element in the body of the function defining the method.If so, this string is taken as self-documentation for the method (seethe section on \dQuote{Writing Reference Methods} for details).If no topic is given or if the topic is not a method name, thedefinition of the class is printed.}\item{\code{$methods(...)}}{ %$With no arguments, returns the names of the reference methods for thisclass.With one character string argument, returns the method of that name.Named argumentsare method definitions, which will beinstalled in the class, as if they had been supplied in the\code{methods} argument to \code{setRefClass()}.Supplying methods in this way, rather than in the call to\code{setRefClass()}, is recommended for the sake of clearer sourcecode.See the section on \dQuote{Writing Reference Methods} for details.All methods for a class should be defined in the source code thatdefines the class, typically as part of a package.In particular, methods can not be redefined in a class in an attachedpackage with a namespace: The class method checks for a lockedbinding of the class definition.The new methods can refer to any currently defined method by name(including other methods supplied in this call to\code{$methods()}). %$Note though that previously defined methods are not re-analyzedmeaning that they will not call the new method (unless it redefines anexisting method of the same name).To remove a method, supply \code{NULL} as its new definition.}\item{\code{$fields()}}{ %$}{Returns a list of the fields, each with its corresponding class.Fields for which an accessor function was supplied in the definitionhave class \code{"activeBindingFunction"}.}\item{\code{$lock(...)}}{ %$}{The fields named in the arguments are locked; specifically, after thelock method is called, the field may be set once. Any further attemptto set it will generate an error.If called with no arguments, the method returns the names of thelocked fields.Fields that are defined by an explicit accessor function can not belocked (on the other hand, the accessor function can be defined togenerate an error if called with an argument).All code to lock fields should normally be part of the definition of aclass; that is, the read-only nature of the fields is meant to be partof the class definition, not a dynamic property added later.In particular, fields can not be locked in a class in an attachedpackage with a namespace: The class method checks for a lockedbinding of the class definition. Locked fields can not besubsequently unlocked.}\item{\code{$trace(what, ..., classMethod = FALSE)}}{ %$}{Establish a traced version of method \code{what} for objects generatedfrom this class. The generator object tracing works like the\code{$trace()}%$method for objects from the class, with two differences.Since it changes the method definition in the class object itself,tracing applies to all objects, not just the one on which the tracemethod is invoked.Second, the optional argument \code{classMethod = TRUE} allows tracingon the methods of the generator object itself.By default, \code{what} is interpreted as the name of a method in theclass for which this object is the generator.}\item{\code{$accessors(...)}}{ %$}{A number ofsystems using the OOP programming paradigm recommend or enforce\emph{getter and setter methods}corresponding to each field, rather than direct access by name.If you like this style and want to extract a field named \code{abc}by \code{x$getAbc()} and assign it by\code{x$setAbc(value)},the \code{$accessors} %$}method is a convenience function that creates such getter and setter methods for thespecified fields.Otherwise there is no reason to use this mechanism. In particular, ithas nothing to do with the general ability to define fields byfunctions as described in the section on \dQuote{Reference Objects}.}} %% end of \describe} %% end of \section\section{Implementation; Reference Classes as S4 Classes}{Reference classes are implemented as S4 classes with a data part oftype \code{"environment"}.Fields correspond to named objects in the environment.A field associated with a function is implemented as an\link[=bindenv]{active binding}.In particular, fields with a specified class are implemented as aspecial form of active binding to enforce valid assignment to thefield.As a related feature, the element in the \code{fields=} list suppliedto \code{setRefClass} can be an \emph{accessorfunction}, a function of one argument that returnsthe field if called with no argument or sets it to the value of theargument otherwise.Accessor functions are used internally and for inter-system interfaceapplications, but not generally recommended as they blur the conceptof fields as data within the object.A field, say \code{data}, can be accessed generally by an expressionof the form \code{x$data} %$}for any object from the relevant class.In an internal method for this class, the field can be accessed by the name\code{data}.A field that is not locked can be set by an expression of the form\code{x$data <- value}.%$Inside an internal method, a field can be assigned by an expression of the form\code{x <<- value}.Note the \link[=assignOps]{non-local assignment} operator.The standard \R interpretation of this operator works to assign it inthe environment of the object.If the field has an accessor function defined, getting and settingwill call that function.When a method is invoked on an object, the function defining the method isinstalled in the object's environment, with the same environment as theenvironment of the function.Reference classes can have validity methods in the same sense as anyS4 class (see \code{\link{setValidity}}).Such methods are often a good idea; they will be called by calling\code{\link{validObject}} and a validity method, if one is defined,will be called when a reference object is created (from version 3.4 of\R on).Just remember that these are S4 methods. The function will be calledwith the \code{object} as its argument. Fields and methods must beaccessed using \code{$}.%$\emph{Note: Slots.} Because of the implementation, new reference classes can inherit fromnon-reference S4 classes as well as reference classes, and can includeclass-specific slots in the definition.This is usually a bad idea, if the slots from the non-referenceclass are thought of as alternatives to fields.Slots will as always be treated functionally.Therefore, changes to the slots and the fields will behave inconsistently,mixing the functionaland reference paradigms for properties of the same object,conceptually unclear and prone to errors.In addition, the initialization method for the class will have to sortout fields from slots, with a good chance of creating anomalousbehavior for subclasses of this class.Inheriting from a \link[=setClassUnion]{class union}, however, is a reasonable strategy (withall members of the union likely to be reference classes).}\section{Debugging}{The standard \R{} debugging and tracing facilities can be applied toreference methods.Reference methods can be passed to \code{\link{debug}} and itsrelatives from an object to debug further method invocations on thatobject; for example, \code{debug(xx$edit)}. %$Somewhat more flexible use is available for a reference method versionof the \code{\link{trace}} function.A corresponding \code{$trace()} %$reference method is available foreither an object or for the reference class generator(\code{xx$trace()} or \code{mEdit$trace()} in the example below).Using \code{$trace()} on an object sets up a tracingversion for future invocations of the specified method for thatobject.Using \code{$trace()} on the generator for the class sets up atracing version for all future objects from that class (and sometimes forexisting objects from the class if the method is not declared orpreviously invoked).In either case, all the arguments to the standard \code{\link{trace}}function are available, except for \code{signature=} which ismeaningless since reference methods can not be S4 generic functions.This includes the typical style \code{trace(what, browser)} forinteractive debugging and \code{trace(what, edit = TRUE)} to edit thereference method interactively.}\references{Chambers, John M. (2016)\emph{Extending R},Chapman & Hall.(Chapters 9 and 11.)}\examples{## a simple editor for matrix objects. Method $edit() changes some## range of values; method $undo() undoes the last edit.mEdit <- setRefClass("mEdit",fields = list( data = "matrix",edits = "list"))## The basic edit, undo methodsmEdit$methods(edit = function(i, j, value) {## the following string documents the edit method'Replaces the range [i, j] of theobject by value.'backup <-list(i, j, data[i,j])data[i,j] <<- valueedits <<- c(edits, list(backup))invisible(value)},undo = function() {'Undoes the last edit() operationand update the edits field accordingly.'prev <- editsif(length(prev)) prev <- prev[[length(prev)]]else stop("No more edits to undo")edit(prev[[1]], prev[[2]], prev[[3]])## trim the edits listlength(edits) <<- length(edits) - 2invisible(prev)})## A method to automatically print objectsmEdit$methods(show = function() {'Method for automatically printing matrix editors'cat("Reference matrix editor object of class",classLabel(class(.self)), "\n")cat("Data: \n")methods::show(data)cat("Undo list is of length", length(edits), "\n")})xMat <- matrix(1:12,4,3)xx <- mEdit(data = xMat)xx$edit(2, 2, 0)xxxx$undo()mEdit$help("undo")stopifnot(all.equal(xx$data, xMat))utils::str(xx) # show fields and names of methods## A method to save the objectmEdit$methods(save = function(file) {'Save the current object on the filein R external object format.'base::save(.self, file = file)})tf <- tempfile()xx$save(tf)\dontshow{load(tf)unlink(tf)stopifnot(identical(xx$data, .self$data))}\dontrun{## Inheriting a reference class: a matrix viewermv <- setRefClass("matrixViewer",fields = c("viewerDevice", "viewerFile"),contains = "mEdit",methods = list( view = function() {dd <- dev.cur(); dev.set(viewerDevice)devAskNewPage(FALSE)matplot(data, main = paste("After",length(edits),"edits"))dev.set(dd)},edit = # invoke previous method, then replotfunction(i, j, value) {callSuper(i, j, value)view()}))## initialize and finalize methodsmv$methods( initialize =function(file = "./matrixView.pdf", ...) {viewerFile <<- filepdf(viewerFile)viewerDevice <<- dev.cur()dev.set(dev.prev())callSuper(...)},finalize = function() {dev.off(viewerDevice)})## debugging an object: call browser() in method $edit()xx$trace(edit, browser)## debugging all objects from class mEdit in method $undo()mEdit$trace(undo, browser)}\dontshow{removeClass("mEdit")resetGeneric("$")resetGeneric("initialize")} %$}\keyword{ programming }\keyword{ classes }