Getters and setters in R
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
When I first started using R, one of the things that attracted me was its claim to be an object-oriented programming (OOP) language. Coming from a Java background, I was used to designing software with OOP concepts like encapsulation and inheritance but, when I turned my hand to R, I quickly realized that “object-oriented” meant something subtlely different.
For those who are interested, the technical detail is explained at length in this paper and this blog (with examples). But what I want to do here is quickly illustrate how you can implement the common get/set method structure in R for a slightly different purpose.
In “traditional” OOP, you might have an object like a Shape
with some attribute, say its area. In Java, this attribute would be accessed and altered using get and set methods, as in:
Shape s = new Shape();
s.setArea(10); // set the attribute value
int area = s.getArea(); // get the attribute value
Using this pattern offers advantages like protecting access to the value of the area
field and ensuring that only valid values are set. While there is some disagreement about whether or not mutator methods represent good practice, every OOP coder must have had at least one occasion where a getter/setter was needed.
Which brings us back to R. I recently had a problem where I wanted to use something like a getter/setter in order to access a global variable consistently, from both inside and outside functions. Since variable scoping in R isn’t very intuitive, I wasn’t sure how to do this at first and so I thought the get/set paradim might be helpful, even though the value I was getting and setting wasn’t really associated with an object.
Here’s what I ended up using. The trick is to create an explicit environment that stores the variable’s value behind the scenes, so that the user doesn’t have to worry about scope.
# Declare an explicit environment to hold the variable e1 <- new.env() # Sets the value of the variable setArea <- function(value) { assign("area", value, env=e1) } # Gets the value of the variable getArea <- function() { return(get("area", e1)) }
Again, this isn’t really object-oriented programming as I’m not manipulating an object (other than the environment e1
) but the get/set pattern has an OOP pedigree. So if you’re coming from a Java or C++ background and are having trouble figuring out variable scoping, the above code might be useful for you. However if you want to do proper object-oriented getting and setting, I highly recommend John Myles White’s example of R object-oriented polymorphism in get/set methods.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.