RMI / RMI/resources

Refactoring `<<-`: Thread on function-specific and package-specific environments

Open
#287 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

best-practice refactoring
Dominant language
No language data
Stars
17
Forks
5
PR merge metrics
No merged PRs in 30d

Description

If you are curious about the use of private environments for functions and packages, have a read of this nice R-package-devel thread!

https://www.mail-archive.com/r-package-devel@r-project.org/msg07413.html

This offers some ideas we may use to easily refactor <<- in our code so that we touch the least code and make it substantially safer. The entire thread is worth reading but one notable way is to wrap our code in local().

# Define a variable in the global environment
variable <- 0
set_variable <- function(x) {
  variable <<- 99
  variable
}

# set_variable() dangerously overwrites the `variable` in the global environment
variable <- 1
set_variable()
#> [1] 99
variable == 1
#> [1] FALSE

set_variable2 <- local({
  variable <- 0
  function(x) {
    variable <<- 99
    variable
  }
})

# set_variable2() no longer overwrites the `variable` in the global environment
variable <- 1
set_variable2()
#> [1] 99
variable == 1
#> [1] TRUE

# Of course you can use set_variable2() inside other funcitons
use_variable <- function(x) {
  variable <- set_variable2()
  x + variable
}

use_variable(1)
#> [1] 100

Created on 2021-11-30 by the reprex package (v2.0.1)

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Read the linked R-package-devel thread first, focusing on its discussion of function-specific and package-specific environments and the use of local(). The issue names no files or tests, so the next step is to identify the current uses of <<- in the project and define which ones should be refactored. Done means a safer, agreed-upon refactoring with no unintended global-environment changes.

Written by the indexing model from the issue text.

Assessment

Tech stack
r
Domain
tooling
Issue type
Refactor
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.