ropensci / datapack

An R package to handle data packages
https://docs.ropensci.org/datapack
44 stars 9 forks source link

fix inability to debug S4 methods #130

Open mbjones opened 3 years ago

mbjones commented 3 years ago

We implement methods in S4 as anonymous functions which are used within the setMethod call to define a method. Because of this, the R debugger does not have access to the source code for that implementation, and debugging is much harder. In addition, IDE tools like RStudio have function lists that are less than useful (just lists of undifferentiated anonymous functions). To fix this, I propose refactoring our code to eliminate use of these anonymous functions by creating non-exported private functions in each class. For example, our current code has methods defined like:

setGeneric("getSize", function(x, ...) { standardGeneric("getSize") })

setMethod("getSize", "DataPackage", { 
    function(x) {
        return(length(x@objects))
    }
})

and I propose we change that to:

setGeneric("getSize", function(x, ...) standardGeneric("getSize") )

getSize_ <- function(x) {
    return(length(x@objects))
}

setMethod("getSize", "DataPackage", getSize_)

The new non-exported getSize_ function now is visible to debugging code and IDEs. In addition, note that I now removed the anonymous block wrapping the standardGeneric call, as recommended by Hadley Wickham in Advanced R.

I've checked in an example of how this works for the DataPackage class in the feature-debuggable-S4 branch. We would need to implement this for all o the classes, which will take a bit of time but is fairly rote if done without other functional changes.

@gothub @amoeba Comments and thoughts appreciated.