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.

1 Like

Sorry, I think, we don’t need this - and should be careful to adapt ODK to MS Excel. Nested Ifs are common in programming languages.

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