Nested if() alternatives

Recently I fell into the messiness of nested if() expression such as:

if(${score} > 90, "A", if(${score} > 80, "A-", if(${score} > 70, "B", if(${score} > 60, "C", "F"))))

In Excel we have formulas like IFS() and SWITCH() which provide better experience than nested if(), I wish we had similar functions in ODK XForms.

I disagree - I would find this useful. While I agree that you can accomplish this with nested IF() statements, it quickly becomes unreadable in Excel. CASE/MATCH, SWITCH, or IFS() are common in many programming languages to deal with this case.

My vote would be for a SWITCH() style case/match. In the scenario proposed by @Sadiq_Khoja, I can imagine three syntaxes:

# Option A: more verbose.  Default case as the end.
SWITCH(${score} > 90, "A", ${score} > 80, "A-", ${score} > 70, "B", ${score} > 60, "C", "F")

# Option B: more terse; potentially confusing with “.” syntax
SWITCH(${score}, . > 90, "A", . > 80, "A-", . > 70, "B", . > 60, "C", "F")

# Option C: most terse; no dot syntax.
SWITCH(${score}, > 90, "A", > 80, "A-", > 70, "B", > 60, "C", "F")

In all cases, it would be nice if both expressions and direct matches were supported. In other words:


SWITCH(${score}, -1, "Negative Sentiment", 0, "Undecided", 1, "Positive Sentiment", "NA")

I suppose that a “default” case would always need to be provided. Or maybe one could count arguments to figure out if a default case was provided or not and change the function logic accordingly.

It would be useful function for sure, especially for bucketing numeric results where it's not possible to have a look up table with every value

This just came up in conversation in @Sadiq_Khoja so wanted to share some quick thoughts!

We have a history of borrowing function signatures from Excel. I think that has served us well where possible because people who write forms also often have familiarity with Excel and many other systems use it as an example as well.

I'm in favor of option A from @jniles with function name ifs which would exactly match Excel: https://support.microsoft.com/en-us/office/ifs-function-36329a26-37b2-467c-972b-4a39bd951d45

I'd like to avoid having multiple signatures if we can. In this case, ${score}, -1, "Negative" is less explicit than ${score} = -1, "Negative" and it doesn't feel like it is much easier to remember or read.