Purpose: reduce tedium of S4 class definition

Given a prototypical list of elementary R data it is trivial but tedious to define a valid S4 class with appropriate getter and setter methods. DrS4's ClassSupport class helps with this.

Example: Turtle

Stuart Lee's blog post on S4 inspires the default parameter settings in the clgen function.

suppressPackageStartupMessages(library(DrS4))
args(clgen)

Generate the basic definitions

Try it:

tt = clgen()
tt

Learn a little more about this infrastructure:

getClass(class(tt))

We dump the code defining the class and its get/set methods.

dumpcs(tt)

To use the code, we can source it, or place in a package.

tf = tempfile()
dumpcs(tt, tf)
source(tf)
tur = new("Turtle")
tur
path(tur)
path(tur) = matrix(c(1,1), nr=1)
tur

Extend the class

Stuart showed how a more functional turtle can be defined -- one that holds a pen. We'll need a new definition and new getters and setters.

We defined a method on our ClassSupport class to produce the new class.

newprops = list(colour = "pink", thickness = 1, on = FALSE)
nn = extendClassSupport(tt, newprops, "TurtleWithPen")
nn
dumpcs(nn)

We can now source that code to allow composition of methods for TurtleWithPen.

Envoi

There is something unsavory about this approach to code generation. I produced it in the face of a task involving a configuration object that seems to require many slots. I wanted to avoid the temptation to use simple functions and the at sign. My hope is that programs along the lines of those demonstrated here will help lower the barrier to adoption of formal class and method definitions in R programming. There are surely many improvements to be made in what has been proposed here.



vjcitn/DrS4 documentation built on Oct. 4, 2021, 10:13 p.m.