r-lib / R6

Encapsulated object-oriented programming for R
https://R6.r-lib.org
Other
404 stars 56 forks source link

Guidance on declaration and default values of a field #170

Open jennybc opened 5 years ago

jennybc commented 5 years ago

Summarizing a conversation in Slack.

Consider this snippet from the vignette:

library(R6)

Person <- R6Class("Person",
  public = list(
    name = NULL,
    hair = NULL,
    initialize = function(name = NA, hair = NA) {
      self$name <- name
      self$hair <- hair
      self$greet()
    },
    set_hair = function(val) {
      self$hair <- val
    },
    greet = function() {
      cat(paste0("Hello, my name is ", self$name, ".\n"))
    }
  )
)

Nitpick: the default NA values should probably be NA_character_ to signal the expected type.

How do you decide to set name and hair to NULL when declared in the public list and then set NA as the default value in $initialize()?

After much discussion, we reached a few conclusions re: a basic workflow, when there's no specific reason to do otherwise:

cc and thanks @gaborcsardi @hadley

hadley commented 5 years ago

Example of something like "single responsibility principle"?