Skip to content

Commit

Permalink
More on S3
Browse files Browse the repository at this point in the history
  • Loading branch information
hadley committed Feb 6, 2017
1 parent df3ac1c commit 7a946e7
Show file tree
Hide file tree
Showing 2 changed files with 121 additions and 85 deletions.
18 changes: 18 additions & 0 deletions OO-essentials.Rmd
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,24 @@ The following chapters describe each system in turn, starting with base types. Y

You'll need the pryr package, `install.packages("pryr")`, to access useful functions for examining OO properties.

## Why OO?

The primary use of OO programming in R is for print, summary and plot methods. These methods allow us to have one generic function, e.g. `print()`, that displays the object differently depending on its type: printing a linear model is very different to printing a data frame.

## Why generic functions?

Compare pipe with method chaining.

This is a different school of though to most popular programming languages, but is a good fit to the problem of data analysis. Knowing this fact probably won't help you much in your day-to-day programming, but it will avoid some fundamental confusing if you're coming from another OO programmming language. \index{functions!generics|see{generics}} \index{S3!generics} \index{generics!S3}

```{r, eval = FALSE}
class.method(arg1, arg2)
class$method(arg1, arg2)
method(arg1, arg2, arg3)
```

(In fact this message is so powerful that I've talked to programmers who moved to R from javascript and it took them a while to figure out that they're not calling the `frame` method of the `data` object.)

## S4 {#s4}

S4 works in a similar way to S3, but it adds formality and rigour. Methods still belong to functions, not classes, but: \index{objects!S4|see{S4}} \index{S4}
Expand Down
Loading

0 comments on commit 7a946e7

Please sign in to comment.