It makes sense that in general avoiding global state is good practice, especially in production code. When prototyping, however, it can be useful (I think). What is the idiomatic way to define semi-constants that multiple functions depend on? By semi-constants I mean variables (typically numbers, but they don’t have to be) that a) lots of functions reference and b) whose value doesn’t change much, e.g. they would be constants in production code but in interactive usage, the user may wish to experiment with different values.
A silly non-realistic but hopefully illustrative example: suppose I am interested in the
k-th largest and smallest elements of arrays. I might have functions like
k = 3
# reads global k
# also reads global k
k_smallest = get_kth_smallest(arr)
k_largest = get_kth_largest(arr)
In this case, especially for interactive use, it’s convenient to rely on global
k; the user knows that
k changes iff the user changes it. But it’s bad to make
const, because then the user can’t experiment with changing
k - the compiled functions won’t update. The value
k could be passed around as an argument to every function, but if many different functions rely on the value of
k, then pretty much every function has to accept
k as an argument so when that function calls another function, the value of
k can be passed along. That’s already ugly with a handful of functions and one constant, and gets really bad with many functions and many constants.
Is the trick to have each function accept default arguments referencing a non-const global variable, e.g.
function get_kth_smallest(k = k)? That way within the function there’s no reference to global state? In some tiny benchmarks I did, this seems to have a large relative but negligible absolute performance cost relative to using