[Rd] S4 classes and methods with optional arguments

Seth Falcon sfalcon at fhcrc.org
Tue Feb 14 19:42:52 CET 2006

On 14 Feb 2006, mtmorgan at fhcrc.org wrote:

> It seems to me like the generic should (always?) just have arguments
> used for dispatch -- stream, in this case -- and that methods then
> specify default values. 

There are advantages to adding named arguments to a generic to define
the expected interface.  These 'extra' args may not be *needed* for
dispatch in the sense that the first arg may be enough to decide what
method you want.

So IMO, there are two reasons to put an arg in a generic:

1. You really want to dispatch on it.
2. You want to define an interface and can handle the fact that you
   will have to also dispatch on it.

I guess my point is that for downstream developers extending your
generic and for the sake of documentation, relying too much on '...'
can make things difficult.

> To also dispatch on the second argument, one
> might
> setGeneric("rstream.sample",
> function( stream, n, ... ) standardGeneric("rstream.sample"))
> setMethod("rstream.sample", c( "rstream.sample", "numeric" ),
> function( stream, n, ... ) { code } )
> setMethod("rstream.sample", c( "rstream.sample", "missing" ),
> function( stream, n, ... ) rstream.sample( stream, n = 1 ))

And here I might offer a slight improvement.  Putting the default
value in the signature of the function will give automated tools a
chance to document:

  setMethod("rstream.sample", c("rstream.sample", "missing"),
            function( stream, n=1, ...) rstream.sample(stream, n))

+ seth

More information about the R-devel mailing list