Closures in Programming – Why Use Them?

functional programmingprogramming practicesswift-language

After reading many posts explaining closures here I'm still missing a key concept: Why write a closure? What specific task would a programmer be performing that might be best served by a closure?

Examples of closures in Swift are accesses of an NSUrl and using the reverse geocoder. Here is one such example. Unfortunately, those courses just present the closure; they do not explain why the code solution is written as a closure.

An example of a real world programming problem that might trigger my brain to say, "aha, I should write a closure for this", would be more informative than a theoretical discussion. There is no shortage of theoretical discussions available on this site.

Best Answer

First of all, there is nothing that is impossible without using closures. You can always replace a closure by an object implementing a specific interface. It's only a matter of brevity and reduced coupling.

Second, keep in mind that closures are often used inappropriately, where a simple function reference or other construct would be more clear. You shouldn't take every example you see as a best practice.

Where closures really shine over other constructs is when using higher-order functions, when you actually need to communicate state, and you can make it a one-liner, as in this JavaScript example from the wikipedia page on closures:

// Return a list of all books with at least 'threshold' copies sold.
function bestSellingBooks(threshold) {
  return bookList.filter(
      function (book) { return book.sales >= threshold; }
    );
}

Here, threshold is very succinctly and naturally communicated from where it is defined to where it is used. Its scope is precisely limited as small as possible. filter doesn't have to be written to allow for the possibility of passing client-defined data like a threshold. We don't have to define any intermediate structures for the sole purpose of communicating the threshold in this one small function. It's entirely self-contained.

You can write this without a closure, but it will require a lot more code, and be harder to follow. Also, JavaScript has a fairly verbose lambda syntax. In Scala, for example, the entire function body would be:

bookList filter (_.sales >= threshold)

If you can however use ECMAScript 6, thanks to the fat arrow functions even the JavaScript code becomes much simpler and can be actually put on a single line.

const bestSellingBooks = (threshold) => bookList.filter(book => book.sales >= threshold);

In your own code, look for places where you generate a lot of boilerplate just to communicate temporary values from one place to another. These are excellent opportunities to consider replacing with a closure.