Shut it Down

Object-Oriented Programming with S3 and R6 in R

Richie Cotton

Data Evangelist at DataCamp

ch5_3-Shut-it-down.003.png

Object-Oriented Programming with S3 and R6 in R

ch5_3-Shut-it-down.004.png

Object-Oriented Programming with S3 and R6 in R

 

 

 

initialize() customizes startup

finalize() customizes cleanup

Object-Oriented Programming with S3 and R6 in R
thing_factory <- R6Class(
  "Thing",
  private = list(
    ..a_field = 123
  ),
  public = list(

initialize = function(a_field) { if(!missing(a_field)) { private$a_field = a_field } },
finalize = function() { message("Finalizing the Thing") }
) )
Object-Oriented Programming with S3 and R6 in R

 

a_thing <- thing_factory$new()
rm(a_thing)
gc()
Finalizing the Thing
         used (Mb) gc trigger (Mb) max used (Mb)
Ncells 443079 23.7     750400 40.1   592000 31.7
Vcells 718499  5.5    1308461 10.0  1092342  8.4
Object-Oriented Programming with S3 and R6 in R
library(RSQLite)
database_manager_factory <- R6Class(
  "DatabaseManager",
  private = list(

conn = NULL
), public = list(
initialize = function(a_field) { private$conn <- dbConnect("some-database.sqlite") },
finalize = function() { dbDisconnect(private$conn) }
) )
Object-Oriented Programming with S3 and R6 in R

Summary

  • finalize() cleans up after R6 objects
  • It is useful when working with databases
  • It gets called during garbage collection
Object-Oriented Programming with S3 and R6 in R

Let's practice!

Object-Oriented Programming with S3 and R6 in R

Preparing Video For Download...