I am writing my first R package and I am trying to figure out what the best way to assign values to a slot in an S4 object, keeping in mind that end-users shouldn't have to fuss with the details of the S4 class structures being used. Which of the following is best?
Accessing slot directly using
object@MySlot <- value
:I understand that this bad practice (e.g., this Q&A).
Using
slot(object, "MySlot") <- value
:The R help says there isn't checking when getting the values, but there is checking when setting (assuming
check
hasn't been set toFALSE
). This sounds reasonable to me, and strikes me as a nice way to do it because I don't have to code my own get/set methods as per below.Using custom methods with
setReplaceMethod()
:How does this approach compare against the second option above? It's more work to produce the necessary get/set methods, but I can more explicitly be sure that the values being written to the slots are valid for that slot type.
setGeneric("MySlot", function(object) { standardGeneric("MySlot") }) setMethod("MySlot", signature = "MyClass", definition = function(object) { return(object@MySlot) }) setGeneric("MySlot<-", function(object, value) { standardGeneric("MySlot<-") }) setReplaceMethod("MySlot", signature="MyClass", function(object, value) { object@MySlot<- value validObject(object) # could add other checks return(object) })