From jmc at r-project.org  Wed Feb 22 20:55:28 2012
From: jmc at r-project.org (John Chambers)
Date: Wed, 22 Feb 2012 11:55:28 -0800
Subject: [Rd] Private fields in reference classes (was: Private
 Variables in R5-Classes possible?)
In-Reply-To: <4F437AEC.2060401@uni-duesseldorf.de>
References: <4F437AEC.2060401@uni-duesseldorf.de>
Message-ID: <4F454830.6020502@r-project.org>

(Can we please follow the terminology in the ?ReferenceClasses 
documentation.  Creativity is fine but here we need communication)

This has come up (once) before off-list.  It could be made part of 
reference classes via a general rewriting that would improve efficiency 
as well.  Not imminent, but it would be good to know of other 
applications, including why they are useful.

Meanwhile, it could be implemented for a subclass of reference classes, 
by adding a special field that lists the private (or public, if you 
like) fields, and then implementing  S4 methods for "$"  and "$<-" that 
check there for disallowed/allowed names.  As presumably one wants, this 
leaves  methods in the class free to use the private fields.

John

On 2/21/12 3:07 AM, Claus Jonathan Fritzemeier wrote:
> Hi list,
>
> is there a way to define some kind of private Variable?
>
> I would like to prevent the user from manipulating fields on his own, 
> in order to not destroy data structures.
>
> The problem is, that as soon as the variable exists in the environment 
> it is accessible via t$secret_value.
>
> test <- setRefClass("test", fields=list(
> secret = function(value){
> cat("the function was called\n")
> if(missing(value)){
> if(exists("secret_value", envir=.self at .xData)){
> return(get("secret_value", envir=.self at .xData, inherits = F))
> }
> else{
> return(NULL)
> }
> }
> assign("secret_value", value=value, , envir=.self at .xData)
> }
> ) )
>
> > t <- test$new()
> > t$secret
> the function was called
> NULL
> > t$secret_value
> Error in envRefInferField(x, what, getClass(class(x)), selfEnv) :
> "secret_value" is not a valid field or method name for reference class 
> ?test?
> > t$secret <- "Blub"
> the function was called
> > t$secret_value
> [1] "Blub"
>
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel
>



[Rd] Private fields in reference classes (was: Private Variables in R5-Classes possible?)
John Chambers