I am trying to understand what the purpose of the generic
argument of NextMethod()
is.
Example
# example data
x <- as.Date(c("2022-01-01", "2023-01-01", "1900-01-01", "2024-01-01"))
# gives cumulative maximum as expected
cummax.Date <- function(x, ...) .Date(NextMethod(), cl = oldClass(x))
cummax(x)
#> [1] "2022-01-01" "2023-01-01" "2023-01-01" "2024-01-01"
# gives cumulative minimum as expected
cummin.Date <- function(x, ...) .Date(NextMethod(), cl = oldClass(x))
cummin(x)
#> [1] "2022-01-01" "2022-01-01" "1900-01-01" "1900-01-01"
Best Practice
Quite often, the generic is called explicitely.
cummin.Date <- function(x, ...) .Date(NextMethod(generic = "cummin"), cl = oldClass(x))
cummin(x)
#> [1] "2022-01-01" "2022-01-01" "1900-01-01" "1900-01-01"
Bad Practice - no Difference
However, explicitly calling the generic does not impact the result whatsoever, no matter if it exists or not.
# still returns the cumulative minimum
cummin.Date <- function(x, ...) .Date(NextMethod(generic = "cummax"), cl = oldClass(x))
cummin(x)
#> [1] "2022-01-01" "2022-01-01" "1900-01-01" "1900-01-01"
# still returns the cumulative minimum
cummin.Date <- function(x, ...) .Date(NextMethod(generic = "foobar"), cl = oldClass(x))
cummin(x)
#> [1] "2022-01-01" "2022-01-01" "1900-01-01" "1900-01-01"
NextMethod
uses argumentgeneric
only if it does not find the symbol.Generic
in the calling environment of the method. That happens only in atypical usage:It is undocumented (I think), but visible in the sources of the internal
do_nextmethod
, which usesreadS3VarsFromFrame
(defined elsewhere) to locate.Generic
.I don't think that anyone would recommend assigning to
.Generic
, removing.Generic
, or otherwise callingNextMethod
in a context where.Generic
is not there. Indeed, I think that the advice inhelp("NextMethod")
about.Class
applies here: