I am often in the position to write functions for different types (classes) of objects (arguments). Somehow it never occurred to me, that it would be a good idea to write methods instead of several functions. Besides all other great advantages of generic functions and methods, one main reason for me is simply the number of function names I have to come up with. And the more functions I use in my package the crazier the names. Not good.
A generic function is a function which will do the method dispatch for us.
Meaning that a generic function will decide which method to call depending on
the class of its arguments.
summary is a good example for a generic function,
it will behave differently when calling it on an object of the class
A method is a function which is written for specific classes of its arguments;
although you probably expect specific classes of your arguments for every
function you write. Methods are typically not called directly but by a call to a
generic function. So for the generic function
summary, there are several
methods, for example
summary.lm which are called
depending on the class of the first argument of the call to
advantage over writing functions named
summarylm is that you
don’t need to remember so many (badly chosen) function names.
Define S3 Methods
Typically I try not to write new generic functions because I have to remember
their names, but write new methods for existing generics. A typical example in
my own work are functions like
rbind and also
summary. The simplest
way is to use S3-generics. Their are little formal requirements one has to think
OK, so this is a stupid example for a S3-Method. The only thing you have to do is to write a new function with a certain naming convention. Begin with the name of the generic function, then a dot and then the class for which this method is written for.
Define S4 Methods
S3 method dispatch uses “only” the class of the first argument. Sometimes it might be useful to supply methods not only for the first argument, but for different arguments. I find this especially appealing for plotting methods, where one needs different plots for different combinations of x and y variables (scatter-plot, boxplot, or histogram). Here is a small example: