[Rd] S3 vs S4 classes
Prof Brian Ripley
ripley at stats.ox.ac.uk
Sat Feb 17 18:34:20 CET 2007
On Sat, 17 Feb 2007, Rossi, Peter E. wrote:
> I have developed a package, bayesm, which uses existing classes of
> objects. I would like to add a new class corresponding to objects from
> this package.
>
> I have been reading about classes and all sources tell me that I should
> use so-called "new" or S4 classes.
For new projects, perhaps: the issue is far less clear cut for existing
ones. In particular, the structure of model-fitting classes inherited
from the White Book (lm, glm and so on) is S3 classes, and so related
model-fitting functions (e.g. my polr) fit most naturally into the S3
paradigm.
> However, a major purpose of defining a class for my package would be to
> add methods to the existing generic functions: print, plot, and
> summary. My understanding is that these functions work with the "old"
> or S3 classes.
S4 classes should use show() rather than print(), according to the
established practice (and I think the Green Book, but I do not have it to
hand). Certainly auto-printing uses show() for S4 objects in preference
to print().
> If I want to use S4 classes, do I need to write new generic functions or
> is there as way to "extend" the existing generics to work with S4
> classes and objects. I may be using the wrong word here "extend" but I
> hope that everyone understands the point. If I have to write new generic
> functions, it is a simply matter of registering the pre-existing methods
> based on S3 objects? Or do you basicaly have to start from scratch --
> i.e. the two types of classes, methods and generic functions are
> distinct?
If you define an S4 method for any function, e.g. plot, it becomes S4
generic and after looking for S4 methods will use the previous function
(and if that is S3 generic, it will still look for S3 methods).
To my mind the advantage of S4 classes is that they are what JMC sometimes
calls 'formal' classes: they are rigidly defined. That suits them to new
projects where you can think about the classes you want and define their
structure and relationships in advance. On the other hand, for
development and experimenting that rigid definition can be a
straightjacket. I have moved various model-fitting functions to S4, and
moved them back to S3 in frustration at the lack of fit to existing tools.
--
Brian D. Ripley, ripley at stats.ox.ac.uk
Professor of Applied Statistics, http://www.stats.ox.ac.uk/~ripley/
University of Oxford, Tel: +44 1865 272861 (self)
1 South Parks Road, +44 1865 272866 (PA)
Oxford OX1 3TG, UK Fax: +44 1865 272595
More information about the R-devel
mailing list