[R] S4 vs Reference Classes

Steve Lianoglou mailinglist.honeypot at gmail.com
Tue Sep 13 23:11:17 CEST 2011


Hi,

On Tue, Sep 13, 2011 at 1:54 PM, Joseph Park <jpark.us at att.net> 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.
>   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.
>   Things of interest:
>   Performance (i.e. memory management)
>   Integration compatibility with R packages
>   ??? other issues

I actually don't have much experience with Reference Classes and
(most) all of my R OO(P|D) with S4 (since I'm generally playing w/
bioconductor stuff, which has an S4 mandate).

I'm not sure exactly what you are after, but the way I design many of
my classes to enable them to have *some* pass by reference semantics
is to add a slot of type `environment` to the class def, like so:

setClass("Something",
  representation=representation(x='numeric', cache='environment'),
  prototype=prototype(x=numeric(), cache=new.env()))

Anything that gets put in `cache` is "passed by ref" so to speak. Consider this:

R> s1 <- new("Something", x=10)
R> s1 at cache$by.reference <- 'there can be only 1'

R> s2 <- s1
R> s2 at x
[1] 10

R> s2 at x <- 12
R> s2 at x
[1] 12

R> s1 at x
[1] 10

R> s1 at cache$by.reference
[1] "there can be only 1"

R> s2 at cache$by.reference <- 'and then there were 2'
R> s2 at cache$by.reference
[1] "and then there were 2"

R> s1 at cache$by.reference
[1] "and then there were 2"


Proceed with caution ...

HTH,

-steve

-- 
Steve Lianoglou
Graduate Student: Computational Systems Biology
 | Memorial Sloan-Kettering Cancer Center
 | Weill Medical College of Cornell University
Contact Info: http://cbio.mskcc.org/~lianos/contact



More information about the R-help mailing list