Closures are functions with state

Closures are functions with state

A closure is a programming language concept that combines a function with a reference to an environment during creation time of the function – or simply put: a function combined with some state. But we’ve heard something similar when people talk about objects in programming languages, haven’t we? An object is state combined with functions. So are they interchangeable? Well, up to a certain degree, I’d say, yes. There are use-cases where closures and objects can be used interchangeably and we’ll look into one of them.

Take a simple example. We have a simple list of employees together with their salary:

A simple generic filter function (I know, I know – I said object-oriented approach, but that does not require us to refrain from using regular functions altogether) will allow us to filter the array with any of the available filters.

We have now built a very simple implementation of the so called strategy pattern – the possibility to exchange an algorithm during runtime. This is not perfect for sure but it’s an example simple enough to show the similarities between closures and objects.

</aside>

Let’s do a quick discussion of what we’ve seen so far. Starting from a „traditional“ object oriented approach, we interchanged classes and objects with closures in a completely functional approach but kept the overall concept of the strategy pattern intact. Our closures just carry their „state“ (which is the filter limit(s)) and the algorithm (which is the comparison logic) with them to be moved around our code. Basically the same way as objects created from our filter classes carry their algorithm (the class method filter) and their state (the limit property) around. We can now say that in this given example objects and closure are interchangeable and that closures require far less code than a traditional approach in our case.

That’s why closures really can make sense with simple strategy-pattern-like code that requires algorithms to be configurable and exchangeable. Use cases might be sorting, filtering, calculation, etc. Just always use the right tool for the job and object-oriented and functional approaches go together quite well, I think,