Читать книгу The Big R-Book - Philippe J. S. De Brouwer - Страница 221
6.3.8 Method Dispatch
ОглавлениеIn its most simple form, S4 dispatching is similar to S3 dispatching. However, the implementation for S4 is more powerful. When an S4 generic function dispatches on a single class with a single parent, then S4 method dispatch is no different from the S3 method dispatch.
For practical use, the main difference is how default values are defined. In S4, there is a special class “ANY” that functions as the default.
Similarly to S3, S4 knows about group generics. Further, details can be found in the function documentation (visualize the documentation – as usual – with the command ?S4groupGeneric
. There is also a function to call the “parent method”: callNextMethod()
.
S4groupGeneric()
callNextMethod()
The main advantage of S4 is that it is possible to dispatch on multiple arguments (though it all becomes a little more complicated and abstract). That is the case when you have multiple parent classes. The rules can be found in the documentation of the function Methods
.
Methods()
These aspects require utmost care. Personally, the author believes that this is where the S4 OO implementation stops to be practically relevant. When one needs further dependencies and complexity the S4 method becomes too easy too complex and it might be hard to predict which method will be called.
For this reason, it might be better to avoid multiple inheritance and multiple dispatch unless absolutely necessary.
Finally, there are methods that allow us to identify which method gets called, given the specification of a generic call:
selectMethod(“credit”, list(“CurrAcc”)) ## Method Definition: ## ## function (x, y) ## { ## new_bal <- x@balance + y ## new_bal ## } ## ## Signatures: ## x ## target “CurrAcc” ## defined “CurrAcc”
There is a lot more to say about S4 inheritance and method dispatch, though it is not really necessary in the rest of the book. Therefore, we refer to other literature. For example, “Advanced R” by Wickham (2014) is a great source.