[R] S4 vs Reference Classes

Steve Lianoglou mailinglist.honeypot at gmail.com
Wed Sep 14 22:18:46 CEST 2011


Just wanted to say that embedding a slot in your class that's an
environment (as I shown earlier) will still solve your problem w/o you
having to switch to Ref classes (since you've already done lots of
work for your app in S4).

Let's assume you have a slot `cache` that is an environment, using
your latests examples, let's say it's like this:

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

Let's say "gradient" is something you want to be access by reference,
you can have something like this (setGenerics left out for lack of

setMethod("gradient", "Element", function(x, ...) {
  if (!'gradient' %in% ls(x at cache)) {
    x at cache$gradient <- calc.gradient.from.element(x)
  x at cache$gradient

Then a call to `gradient(my.obj)` will return the gradient if it
already calculated, or it will calc it on the fly and set it into your
object (w/o copying your object) and return it when it's done.

> which is my issue. Without the reference-based approach an object
> in a slot which is then included in another object slot is a copy.
> An update to the original object slot then requires 'extra' code
> to update/synchronize the copy.

Again, this "semi-s4-semi-ref-class" approach would run around this
issue .. but life might get confusing to you (or your users) depending
on what one expects as "normal" behavioR.

Just wanted to try to clear up my original intention (if it wasn't
clear before).


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