Advantages and Disadvantages of Nesting Functions

Suppose I have a function that relies on another function to perform calculations, eg.

skew_add_list <- function(a, b){

    stopifnot(length(a) == length(b))

    skew_add <- function(a,b){
        a + b + rnorm(n = 1, mean = 0, sd = 1)
    }   

    result_list <- lapply(seq_along(a), function(i) skew_add(a[[i]], b[[i]]))

    return(result_list)
}

      

Now it skew_add

is a very specific function and is only used in the body skew_add_list

. So what are the advantages / disadvantages of exiting the functions defined in the above block of code versus splitting them up as in:

skew_add <- function(a,b){
    a + b + rnorm(n = 1, mean = 0, sd = 1)
}   


skew_add_list <- function(a, b){

    stopifnot(length(a) == length(b))

    result_list <- lapply(seq_along(a), function(i) skew_add(a[[i]], b[[i]]))

    return(result_list)
}

      

+3


source to share


2 answers


One of the drawbacks of declaring a nested function is the fact that it will be created inside the functional environment every time you call the "parent" function. This is called the "new beginning" principle. In theory, this can degrade performance if the parent function is often called. But I very much doubt that it will be noticeable in practice.



Personally, I prefer nested function in such cases to improve code readability and not to overflow the global environment.

+2


source


I agree with @ Flame's comments on performance. But the effect can be seen only if the computational time is short or the code parsing time.

In my opinion, nested functions are really useful for reading code. You can think of nested functions as a kind of "module" where nested functions make sense within that module. More or less object oriented method, but using only static methods.



So, in short, when you use a function f2

that will only be called f1

and only makes sense in context f1

, the nest is f2

inside f1

.

Again, just an opinion ...

+1


source







All Articles