hadley / ggplot2-book

ggplot2: elegant graphics for data analysis
https://ggplot2-book.org/
1.55k stars 678 forks source link

Clarification on when to use `ggproto_parent()` #373

Open teunbrand opened 1 year ago

teunbrand commented 1 year ago

In chapter 19.4.5 the following is said about using the ggproto_parent() function:

https://github.com/hadley/ggplot2-book/blob/ff77ea98501a4edbd9c5a95344d4f80140105f7f/internals.qmd#L564

However, that paragraph doesn't give a lot of guidance about when to use Class$method() and when to use ggproto_parent(Class, self)$method(). I think it would help if it was clearer that the Class$method() approach is safe when no reading or writing to/from self happens (i.e. the Class$method() formals doesn't include self), and less safe otherwise. To give an example a difference occurs:

library(ggplot2)

Drink <- ggproto(
  "Drink",
  property = "cold",
  describe = function(self) {
    print(paste0("This drink is ", self$property))
  }
)

Coffee <- ggproto(
  "Coffee", Drink,
  property = "hot",
  describe_parent = function(self) {
    ggproto_parent(Drink, self)$describe()
  },
  describe_class = function(self) {
    Drink$describe()
  }
)

Coffee$describe_parent()
#> [1] "This drink is hot"
Coffee$describe_class() # Yuck!
#> [1] "This drink is cold"

Created on 2023-07-19 with reprex v2.0.2

In the example Coffee$describe() would of course give the correct answer, but that is besides the point.