Get the latest tech news

Avoiding if-else Hell: The Functional Style


Many years ago, I took part in the development of a taxi-hailing mobile app that is still widely used today. I don’t know what kind of code they’re running now, but in those early days, the driver assignment code –if I remember it correctly– was similar in spirit to the grossly simplified example that follows. There are five levels of nested if statements in less than 30 lines of code. It doesn’t look so bad, some might say, but it’s not difficult to imagine how complicated this code can become with just a few more checks…

It doesn’t look so bad, some might say, but it’s not difficult to imagine how complicated this code can become with just a few more checks, such as surge pricing and loyalty programs, among other things. The very first if statement, which checks the maximum allowed distance between a driver and the rider, can be converted into a guard clause to remove one level of nesting since it applies to all cases. With the addition of a decision table, we have completely eliminated nested ifs, and as an added bonus, the driver assignment logic can now be changed by simply editing the conditions array.

Get the Android app

Or read this on Hacker News

Read more on:

Photo of hell

hell

Photo of functional style

functional style

Related news:

News photo

Nike’s New CEO Has One Hell of a Challenge Ahead

News photo

The Bastard Operator from Hell (1999)

News photo

What the hell did I just watch?