Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Public and Private Slots in R?

Tags:

oop

r

When defining classes, does R have any notion of private vs public slots?

If there is no strict feature for this in the language, is there a common naming scheme?

like image 810
Kyle Brandt Avatar asked May 25 '12 13:05

Kyle Brandt


1 Answers

EDIT :

To give a bit of history: In the setClass function an option 'access' was provided to create so-called 'privileged slots' that could only be accessed through getters and setters provided with the class. This would allow to create private slots (by not providing a getter), but this feature has never been implemented. The help page of ?setClass currently reads :

access and version, included for compatibility with S-Plus, but currently ignored.


So there is no such thing as private and public slots, as through the @ notation every slot is reachable. And personally I'm very happy with that, as it allows me to use information from objects that is not readily reachible by using the getters and setters included in the package. It also allows me to economize heavy calculations by avoiding overhead created by getters and setters.

I am not aware of any naming convention for making a distinction between public and "private" slots. You can make the distinction for yourself by preceding the "private" slots with a dot, but that has no effect on how that slots behave. It's also not common practice, as most R programmers don't care about public and private slots. They just don't provide getters and setters for slots that the average user shouldn't reach.

To give a trivial example : the following creates a class with two slots, and a getter and setter for only one slot.

setClass("Example",
  representation(
    aslot = "numeric",
    .ahiddenslot = "character"
  )
)

setGeneric("aslot", function(x) standardGeneric("aslot"))

setMethod("aslot","Example",function(x){
    x@aslot
})

setGeneric("aslot<-", function(x,value) standardGeneric("aslot<-"))

setMethod("aslot<-","Example",function(x,value){
    x@aslot <- value
    x
})

You can also set a show method that just doesn't print out the hidden slot:

setMethod("show","Example",function(object){
  cat("Example with value for aslot: ", object@aslot,"\n")
})

This gives the following normal use :

> X <- new("Example",aslot=1,.ahiddenslot="b")
> X
Example with value for aslot:  1 
> aslot(X)
[1] 1
> aslot(X) <- 3

But the .ahiddenslot is still reachable:

> slot(X,".ahiddenslot")
[1] "b"
like image 148
Joris Meys Avatar answered Nov 15 '22 22:11

Joris Meys