Function Design: if else/switch alternatives

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!

For me if the code is meant to be self documenting and easy for programmer to reason about then you need to come up with good/meaningful function names that act as descriptions for what they do. Names like check1 might make sense for a fragment of stand in code as example of syntactic approaches but I hope you weren't inclined to number your checks and leave it at that.

As I am working with a String as input the (imho) correct answer is switch().

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

I think other considerations depend on use case. If performance is critical and some checks are only meaningful or desired based on success or failure in other tests then some heirarchical structure must be defined. Otherwise if clarity and simplicity is key, and performance is less of a concern, I would consider whether I could make the checks and transforms of the data indepent to were I could apply them all one after the other without concern for heirarchy

You are right of course! This was only as an example to make clear what I mean. The real functions are named and not numbered :smiley: like: is_valid_formula