Rev 44751 | Blame | Compare with Previous | Last modification | View Log | Download | RSS feed
% File src/library/methods/man/Methods.Rd% Part of the R package, http://www.R-project.org% Copyright 1995-2007 R Core Development Team% Distributed under GPL 2 or later\name{Methods}\alias{Methods}\title{General Information on Methods}\description{This documentation section covers some general topics on how methodswork and how the \pkg{methods} package interacts with the rest of R. Theinformation is usually not needed to get started with methods andclasses, but may be helpful for moderately ambitious projects, or whensomething doesn't work as expected.The section \bold{How Methods Work} describes the underlyingmechanism; \bold{Dispatch and Method Selection} provides moredetails on how class definitions determine which methods are used.For additional information specifically about class definitions, see \code{?\link{Classes}}.}\section{How Methods Work}{A generic function is a function that has associated with it acollection of other functions (the methods), all of which agree informal arguments with the generic.Each R package will include methods metadata objectscorresponding to each generic function for which methods have beendefined in that package.When the package is loaded into an R session, the methods for eachgeneric function are \emph{cached}, that is, stored in theenvironment of the generic function along with the methods frompreviously loaded packages. This merged table of methods is used todispatch or select methods from the generic, using class inheritanceand possibly group generic functions (see\code{\link{S4groupGeneric}}) to find an applicable method.See the \bold{Dispatch} section below.The caching computations ensure that only one version of eachgeneric function is visible globally; although different attachedpackages may contain a copy of the generic function, these are infact identical.The methods for a generic are stored according to thecorresponding \code{signature} for which the method was defined, ina call to \code{\link{setMethod}}. The signature associates oneclass name with each of a subset of the formal arguments to thegeneric function. Which formal arguments are available, and theorder in which they appear, are determined by the \code{"signature"}slot of the generic function. By default, the signature of thegeneric consists of all the formal arguments except \dots, in theorder they appear in the function definition.Trailing arguments in the signature will be \emph{inactive} if nomethod has yet been specified that included those arguments.Inactive arguments are not needed or used in labeling the cachedmethods. (The distinction does not change which methods aredispatched, but ignoring inactive arguments does improve theefficiency of dispatch. Thus, defining the generic signature tocontain the most useful arguments first can help efficiencysomewhat.)All arguments in the signature of the generic function will be evaluated when thefunction is called, rather than using the traditional lazyevaluation rules of S. Therefore, it's important to \emph{exclude}from the signature any arguments that need to be dealt withsymbolically (such as the first argument to function\code{\link{substitute}}). Note that only actual arguments areevaluated, not default expressions.A missing argument enters into the method selection as class\code{"missing"} and non-missing arguments according to their actualclass.As of version 2.4.0 of R, the cached methods are stored in anenvironment object. The names used for assignment are aconcatenation of the class names for the arguments in the activesignature.}\section{Dispatch and Method Selection}{When a call to a generic function is evaluated, a method is selected correspondingto the classes of the actual arguments in the signature.First, the cached methods table is searched for a \emph{direct} match;that is, a method stored under the direct class names.The direct class is the value of \code{class(x)} for each non-missingargument, and class \code{"missing"} for each missing argument.If no method is found directly for the actual arguments in a call to ageneric function, an attempt is made to match the available methods tothe arguments by using \emph{inheritance}.Each class definition potentially includes the names of one or moreclasses that the new class contains. (These are sometimes called the\emph{superclasses} of the new class.)The S language has an additional, explicit mechanism for defining superclasses, the\code{\link{setIs}} mechanism.Also, a call to \code{\link{setClassUnion}} makes the union class asuperclass of each of the members of the union.All three mechanisms are treated equivalently for purposes ofinheritance: they define the \emph{direct} superclasses of aparticular class.The direct superclasses themselves maycontain other classes. Putting all this information together producesthe full list of superclasses for this class.The superclass list is included in the definition of the class that iscached during the R session.Each element of the list describes the nature of the relationship (see\linkS4class{SClassExtension} for details).Included in the element is a \code{distance} slot giving a numericdistance between the two classes.The distance currently is the path length for the relationship:\code{1} for direct superclasses (regardless of which mechanismdefined them), then \code{2} for the direct superclasses of thoseclasses, and so on.In addition, any class implicitly has class \code{"ANY"} as a superclass. Thedistance to \code{"ANY"} is treated as larger than the distance to anyactual class.The special class \code{"missing"} corresponding to missing argumentshas only \code{"ANY"} as a superclass, while \code{"ANY"} has nosuperclasses.The information about superclasses is summarized when a classdefinition is printed.When a method is to be selected by inheritance, a search is made inthe table for all methods directly corresponding to a combination ofeither the direct class or one of its superclasses, for each argumentin the active signature.For an example, suppose there is only one argument in the signature and that the class ofthe corresponding object was \code{"dgeMatrix"} (from the\code{Matrix} package on CRAN).This class has two direct superclasses and through these 4 additional superclasses.Method selection finds all the methods in the table of directlyspecified methods labeled by one of these classes, or by\code{"ANY"}.When there are multiple arguments in the signature, each argument willgenerate a similar list of inherited classes.The possible matches are now all the combinations of classes from eachargument (think of the function \code{outer} generating an array ofall possible combinations).The search now finds all the methods matching any of this combinationof classes.The computation of distances also has to combine distances for theindividual arguments.There are many ways to combine the distances; the currentimplementation simply adds them.The result of the search is then a list of zero, one or more methods,and a parallel vector of distances between the target signature andthe available methods.If the list has more than one matching method, only those corresponding tothe minimum distance are considered.There may still be multiple best methods.The dispatch software considers this an ambiguous case and warns theuser (only on the first call for this selection).The method occurring first in the list of superclasses is selected. By the mechanism of producingthe extension information, this orders the direct superclasses by theorder they appeared in the original call to \code{\link{setClass}},followed by classes specified in \code{\link{setIs}} calls, in theorder those calls were evaluated, followed by classes specified inunions.Then the superclasses of those classes are appended (note that onlythe ordering of classes within a particular generation of superclassescounts, because only these will have the same distance).For further discussion of method selection, see the document \url{http://developer.r-project.org/howMethodsWork.pdf}.All this detail about selection is less important than the realizationthat having ambiguous method selection usually means that you need tobe more specific about intentions.It is likely that some consideration other than the ordering ofsuperclasses in the class definition is more important in determiningwhich method \emph{should} be selected, and the preference may wellbe different for different generic functions. Where ambiguitiesarise, the best approach is usually to provide a specific method forthe subclass.When the inherited method has been selected, the selection is cachedin the generic function so that future calls with the same class willnot require repeating the search. Cached non-direct selections arenot themselves used in inheritance searches, since that could resultin invalid selections.Besides being initiated through calls to the generic function, methodselection can be done explicitly by calling the function \code{\link{selectMethod}}.}\references{The R package \pkg{methods} implements, with a few exceptions, theprogramming interface for classesand methods in the book \emph{Programming with Data} (JohnM. Chambers, Springer, 1998), in particular sections 1.6, 2.7, 2.8,and chapters 7 and 8.While the programming interface for the \pkg{methods} package followsthe reference, the R software is an original implementation, sodetails in the reference that reflect the S4 implementation may appeardifferently in R. Also, there are extensions to the programminginterface developed more recently than the reference.}\seealso{\code{\link{setGeneric}},\code{\link{setClass}}and the document \url{http://developer.r-project.org/howMethodsWork.pdf}.}\keyword{programming}\keyword{classes}\keyword{methods}