design
design copied to clipboard
Mutable state within a package
i.e. the <- new.new(parent = emptyenv()) or similar.
https://twitter.com/ID_AA_Carmack/status/575788622554628096 via @jimhester
Note about using this approach in a package re: caching value.
Context: I am calling an API and want to cache the list result. I am using an internal environment in the package, and tried the the$ convention. For caching, I used rlang::env_cache()
# Defining internal state value would be this way
the$active_version <- "2.10"
# Resetting the state to no active version would be mean setting to NULL or ""
the$active_version <- NULL # ""
# But caching value would require `env_cache`
get_cached_val <- function() { env_cache(the, "val", default) }
# Resetting / clearing the cache can't be done by setting to NULL
the$val <- NULL
# because cached value would still be return by `env_cache`.
# It requires `env_unbind()` probably
env_unbind(the, "val")
For this type of usage, is this still interesting using the$val <- over using env_bind() ?
Should "unset state" be a value with NULL or an unbinded value ?
In both case the$val returns NULL but in one case env_has(the, "val") is FALSE.
When env_has(the, "val") is TRUE in any case, value can't currently be cached with env_cache()
library(rlang)
the <- new_environment()
the$val
#> NULL
env_has(the, "val")
#> val
#> FALSE
the$val <- NULL
env_has(the, "val")
#> val
#> TRUE
the$val
#> NULL
I am putting this here for thoughts - no expectation right now on an answer