Search code examples
ooprreference-class

define class methods and class variables in R5 reference class


I want to know the correct way to define the class methods and class variable in R5 reference class.

Here is an example:

> # define R5 class XX
> # member variable: ma
> # member method: mfa
> XX <- setRefClass("XX",
+   fields = list(ma = "character"),
+   methods = list(
+     mfa = function() return(paste(ma, "*"))
+     ))
> 
> XX
Generator object for class "XX":

Class fields:

Name:         ma
Class: character

 Class Methods:  
    "callSuper", "copy", "export", "field", "getClass", "getRefClass", "import", "initFields", 
"mfa"


 Reference Superclasses:  
    "envRefClass"

> # create an instance of XX
> x <- XX$new(ma="ma")
> 
> # call member method refering to the member variable.
> x$mfa()
[1] "ma *"
> 
> # here, I define *class* variable
> XX$cc <- "cc"

> # contents of XX
> ls(XX)
[1] "cc"        "className" "def"       "methods"   "new"      

> # here, I define member method referring to the class var.
> XX$methods(mfc = function() {
+   return(XX$cc)
+ })

> # it does work.
> x$mfc()
[1] "cc"

The XX$cc <- "cc" behaves as if the cc is class variable of XX, but I'm not sure if this is a correct way.
For example, XX$def <- "hoge" can break the XX class generator.

So, I want to know if there is a standard way to define class variable and methods.

Thanks in advance.


Solution

  • Regarding a "standard" for class variables, no such standard exists. Reference classes are a new feature to R, and to the extent that some aspect of OO isn't documented in the official documentation on reference classes, it's safe to assume that it hasn't yet been standardized.

    As for whether such a standard might appear, I doubt it. Class variables are really just volatile globals in a pseudo-namespace, and relying on external state generally isn't the R way of doing things. The existence of reference classes is already a pretty big concession against this to improve performance.

    But, as you noted, what you've done does work. R is a language for consenting adults, and it won't try to stop you from introducing messiness at your own risk.