[R] Use generic functions, e.g. print, without UseMethod?

Ivan Krylov kry|ov@r00t @end|ng |rom gm@||@com
Fri Aug 11 09:42:22 CEST 2023


On Fri, 11 Aug 2023 09:20:03 +0200
Sigbert Klinke <sigbert using wiwi.hu-berlin.de> wrote:

> I have defined a function 'equations(...)' which returns an object
> with class 'equations'.

> But I did not use 'equations <- function(x, ...)
> UseMethod("equations"). Two questions:
> 
> 1.) Is this a sensible approach?

Quite. If there is little reason for your constructor to be generic
(i.e. there is only one way to construct "equations" objects), it can
stay an ordinary R function. lm() works the same way, for example, and
so do many statistical tests and contributed model functions.

> 2.) If yes, are there any pitfalls I could run in later?

If it later turns out that you need S3 dispatch on the constructor too,
you will need to take care to design its formals to avoid breaking
compatibility with the old code. Ideally, the generic should take (x,
...), with the first argument determining the method that will be
called. If that would conflict with the already-existing code, the
generic can have a different signature and give a different object=
argument to UseMethod(), but the methods will have to follow the
signature of the generic.

-- 
Best regards,
Ivan



More information about the R-help mailing list