[R] S4 vs Reference Classes

Martin Morgan mtmorgan at fhcrc.org
Wed Sep 14 06:17:18 CEST 2011


On 09/13/2011 10:54 AM, Joseph Park wrote:
>
>     Hi, I'm looking for some guidance on whether to use
>     S4 or Reference Classes for an analysis application
>     I'm developing.
>     I'm a C++/Python developer, and like to 'think' in OOD.
>     I started my app with S4, thinking that was the best
>     set of OO features in R. However, it appears that one
>     needs Reference Classes to allow object methods to assign
>     values (other than the .Object in the initialize method)
>     to slots of the object.

With

   setClass("A", representation=representation(slt="numeric"))

a slot can be updated with @<- and an object updated with a replacement 
method

   setGeneric("slt<-", function(x, ..., value) standardGeneric("slt<-"))

   setReplaceMethod("slt", c("A", "numeric"), function(x, ..., value) {
       x at slt <- value
       x
   })

so

 > a = new("A", slt=1)
 > slt(a) = 2
 > a
An object of class "A"
Slot "slt":
[1] 2

The default initialize method also works as a copy constructor with 
validity check, e.g., allowing multiple slot updates

   setReplaceMethod("slt", c("A", "ANY"), function(x, ..., value) {
       initialize(x, slt=as.numeric(value))
   })

 > slt(a) = "1"


>     This is typically what I prefer: creating an object, then
>     operating on the object (reference) calling object methods
>     to access/modify slots.
>     So I'm wondering what (dis)advantages there are in
>     developing with S4 vs Reference Classes.

R's copy-on-change semantics leads me to expect that

b = a
slt(a) = 2

leaves b unchanged, which S4 does (necessarily copying and thus with a 
time and memory performance cost). A reference class might be 
appropriate when the entity referred to exists in a single copy, as 
e.g., an on-disk data base, or an external pointer to a C++ class.

Martin

>     Things of interest:
>     Performance (i.e. memory management)
>     Integration compatibility with R packages
>     ??? other issues
>     Thanks!
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.


-- 
Computational Biology
Fred Hutchinson Cancer Research Center
1100 Fairview Ave. N. PO Box 19024 Seattle, WA 98109

Location: M1-B861
Telephone: 206 667-2793



More information about the R-help mailing list