I'm currently exploring the possibilities of R's Reference Class and I'm trying to wrap my head around customized accessor functions. The manual states for field that:
The element in the list can alternatively be an accessor function, a function of one argument that returns the field if called with no argument or sets it to the value of the argument otherwise. Accessor functions are used internally and for inter-system interface applications. Their definition follows the rules for writing methods for the class: they can refer to other fields and can call other methods for this class or its superclasses. See the section on “Implementation” for the internal mechanism used by accessor functions.
All I've been able to find is using accessor functions in the context of file storage. Being accustomed to private internal variables and input validations I would argue that this is where the input data validation should be, see example below:
Account <-
setRefClass("Account",
fields = list(data = "list",
balance =
function(value){
if (missing(value)){
return(data$balance)
}else{
if (!is.numeric(value))
stop("You can only set the balance to a numeric value!")
data$balance <<- value
}
}),
methods = list(
withdraw = function(x) {
balance <<- balance - x
},
deposit = function(x) {
balance <<- balance + x
}
))
This works as expected:
> a <- Account$new(balance = 0)
>
> a$deposit(10)
> a$balance
[1] 10
>
> a$withdraw(1)
> a$balance
[1] 9
>
> a$balance <- "a"
Error in (function (value) :
You can only set the balance to a numeric value!
What I would like to know if there is a reason for not doing this since it seems like a natural approach but not mentioned in the manual? Is there a good way of completely hiding the data variable, e.g. using .self <- local({data = list(); .self})
at some point.