Hello!
I am currently refactoring a function within an existing package and I am not sure what the "best"/"cleanest" way to approach the overall function design is.
The function takes as arguments one String str_arg
and 3 other Numerics/Strings arg2,...,arg4
.
Depending on the contents of str_arg
different checks are run on the other arguments. There are 10+ valid options that str_args
can represent.
The obvious choice would be to have one long chain of if, else if
and call the check functions in each branch, with as many choices as there are this will be pretty long.
The only other option I came up with would be a kind of lookup table: a data.frame
with a name column and columns for the check function names and then use get()
to do something like this:
check_function1 <- function(x) is.numeric(x)
str_arg <- "option1"
arg1 <- "some input"
df <- data.frame(name = "option1", check = "check_function1")
f_name <- df[df$name == str_arg]$check
get(f_name)(arg1)
This would result in less code but I don't think it is the right choice for readability as the df would need to be defined in some other file to actually have less code in the function.
So currently ìf else
seems better to me but maybe I am missing something obvious?
Thanks for your input!