5

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.

kohske
  • 65,572
  • 8
  • 165
  • 155
  • I don't think there is an equivalent of class methods/variables in the reference object framework. – hadley Apr 22 '11 at 13:28
  • @hadley thanks. then, do you think there is any reason not to implement class methods/variables in R5 class? – kohske Apr 22 '11 at 14:10
  • I just don't think they have any role. Can you provide an example of what you need class variables/methods for? – hadley Apr 22 '11 at 15:56
  • Perhaps there would never be the case where the class var/methods are absolutely necessary. As I'm familiar with the OOP style of C++ where class var/methods are supported, so I just wondered if the R5 system supports them, and if not, why. But anyway, there are many ways to do similar thing as @goodside also says. – kohske Apr 23 '11 at 16:49

1 Answers1

6

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.

goodside
  • 4,429
  • 2
  • 22
  • 32