DEV Community

Gervin Guevarra
Gervin Guevarra

Posted on

Fluent If-Else statements?

Some showerthoughts for the day:

I think it would have been nice if languages support fluent conditional statements.

So instead of

if(condition) {
    someFunction();
} else if (anotherCondition) {
    anotherFunction()
} else {
    doSomething()
}
Enter fullscreen mode Exit fullscreen mode

Maybe have something like

if(condition, someFunction)
    .elseIf(anotherCondition, anotherFunction)
    .else(doSomething)
Enter fullscreen mode Exit fullscreen mode

or go further and make it return a value

var someVar = if(condition, someFunction)
                    .elseIf(anotherCondition, anotherFunction)
                    .else(defaultValue)
Enter fullscreen mode Exit fullscreen mode

Pros:

  • you get a more succinct and arguably more expressive statement
  • if used properly, it may read like a prose

Cons:

  • it's probably unnatural or unintuitive to some people; more cognitive load perhaps?

I'm not actually sure if this already exists elsewhere and I'm too lazy to find out if it does.
But what do you guys think? Is this useful or am I just overthinking it? 😆

Top comments (2)

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

Super easy to implement, although you'd need to call it fif, _if, or something. Not sure of any benefit though. Would likely be slower too

Collapse
 
gervg profile image
Gervin Guevarra

Yeah, I'm also a bit skeptical if this is actually useful. If the goal was to improve readability, how do we prove it?

As for the performance, I think it will be a lesser concern. I'm quite optimistic that the overhead would only be a few nano if not milliseconds. But then again, I haven't tried writing one yet 😅. It's also one of the reason why I said it would have been nice if it's already built in the language. I'm hoping the language designers (implementers?) will find a way to make it as efficient as the good ol' if-else.