There is an apocryphal story told often in the style of a proverb: "Objects are a poor man's closure; closures are a poor man's object". The point of this proverb is to point to the similarities between the two constructs. In this blog post, I will show you what this means and show you how functional programming and Object Oriented programming are connected. In this post, I will be using Ocaml and Java to show the similarities.
Whenever you talk about functional programming, the first thing you end up discussing is state. In this case, state is a good thing rather than a bad thing. So, let us have an example of a closure:
let foo bar =
(fun x -> bar + x)
The expression bar is called a "free variable" in this context. The function foo "closes over" the scope of the anonymous function, which is returned to the caller. Thus state is stored for further use in later calls.
The object oriented equlivient goes like this:
public class Foo {
private Integer bar;
public Foo(Integer bar) {
bar = bar;
}
public Integer add(Integer x) {
return bar + x;
}
}
Notice the scope of bar in both instances. In both instances, bar is saved for later use. The object Foo closes over the scope of bar. In this case the Object performs a similar function as the function above. Of course, there is one major difference between the two. In Java, the state is mutable everwhere; thus, bar can be changed between calls to "add". In the Ocaml case, this is not possible but the effect can be captured by calling foo with another value for bar.
Both Object Oriented languages like Java and multi-paradigm languages like OCaml manage state through scope. In the case of OCaml the smallest unit of scope is the function. In the case of Java, the smallest unit of transferrable scope is the object.
Christopher Yocum
Tags: objects closures
January 13th 2015