Declare variables to be ‘final’

Declare variables to be ‘final’

In R it can happen that a variable is overwritten by accident at a later stage of the script, as there is no clear attribute ‘final’ like in other languages available. Though many people claim, this is just a proof of bad programming style, I do not share this opinion. In my opinion, it might happen that, especially in a larger analysis script that global variables are accidentally named the same and then overwrite the previous. This is especially promoted by the use of Notebooks.

Hence, we would like to have a way to declare variables in R to be final. The most convenient way for that is to use the lockBinding command like this

R> x <- 1 + 2
R> x
[1] 3
R> lockBinding("x", .GlobalEnv)
R> x
[1] 3
R> x <- x + 2
Error: cannot change value of locked binding for 'x'

Using the commandlockBinding, we can lock a variable in a defined environment and after that, it cannot be changed anymore. This is especially useful for global variables that need to be final, but shouldn’t be overused. It is still a piece of good advice to use as many functions as possible to avoid variable overwriting, but for global variables that need to be protected, this function is a handy tool.

To unlock a variable again, you need the unlockBinding command

R> unlockBinding("x", .GlobalEnv)
R> x <- x + 2
R> x
[1] 5

A convenience wrapper of this function is implemented in my `Luke`-package and lock by default in the global environment the variable like this

 R> final("x")

Leave a Reply

%d bloggers like this: