I’ve been working on a little Scala project recently called Open Checkin. Today, I was working on some code to talk to the remote API. Here’s the thing. Imagine Foursquare. If you are in the middle of the city, you pull up a list of venues nearby for you to check in to. Well, those venues aren’t going to be that far away. You might be standing in the middle of the West End or Soho in London and there might be 50 bars, restaurants, pubs and so on near you. Now go out to the middle of the countryside. There might only be 5 venues within 20 miles of you. The search needs to get progressively bigger until you find enough venues.
I have a function that calls the API and then calls a constructor method on the Venue object.
So, easy, right? Nice easy imperative solution. Work out how many results you need. Let’s say 20. Now you start with a small query, and if it hits 20, you return the results. If not, it goes to a bigger query, and if that hits 20, then you return the results. And so on. Just a series of if-else statements. Sort of like this:
Ah, but remember, we don’t have the Java style if statement. if is not a “control structure” as you probably learned in old fashioned imperative programming. Instead, if is an expression. The if-else structure is basically a fancy function that takes three arguments: an expression that returns a boolean, an expression that returns some type T, and another expression that returns the same type T.
It looks like a Java if statement, and given that it’s running on the JVM, it feels like it ought to be a Java if statement. But it isn’t. It’s an if expression.
But there’s no need to panic. If you are thinking about writing a complicated set of five nested if statements, there’s probably a better way of doing it.
A radical idea. Recursion!
The resulting code is, to my mind, much more readable. It also shows how, with about two minutes extra thought, you can make a better solution to a problem even if you don’t have something as allegedly basic and necessary as an conditional control flow structure.