Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Closures are poor man's objects and vice versa" - What does this mean?

Closures are poor man's objects and vice versa.

I have seen this statement at many places on the web (including SO) but I don't quite understand what it means. Could someone please explain what it exactly means?

If possible, please include examples in your answer.

like image 379
missingfaktor Avatar asked Mar 23 '10 05:03

missingfaktor


People also ask

Are closures like objects?

These are analogous to private variables in object-oriented programming, and in fact closures are analogous to a type of object, specifically function objects, with a single public method (function call), and possibly many private variables (the closed-over variables).

Is a closure an object?

You can have a "closure" also be an object. Java's anonymous inner classes close over the final variables in scope. EeLanguage's object definitions are closures, which allows it to avoid the concept of a "class" without using prototypes and yet still having a central module used to spawn new objects of a given type.

What does closing over mean?

​to surround and cover somebody/something.


1 Answers

Objects are poor man's closures.

Consider Java. Java is an object-oriented programming language with no language level support for real lexical closures. As a work-around Java programmers use anonymous inner classes that can close over the variables available in lexical scope (provided they're final). In this sense, objects are poor man's closures.

Closures are poor man's objects.

Consider Haskell. Haskell is a functional language with no language level support for real objects. However they can be modeled using closures, as described in this excellent paper by Oleg Kiselyov and Ralf Lammel. In this sense, closures are poor man's objects.


If you come from an OO background, you'll probably find thinking in terms of objects more natural, and may therefore think of them as a more fundamental concept than closures. If you come from a FP background, you might find thinking in terms of closures more natural, and may therefore think of them as a more fundamental concept than objects.

Moral of the story is that closures and objects are ideas that are expressible in terms of each other, and none is more fundamental than the other. That's all there is to the statement under consideration.

In philosophy, this is referred to as model dependent realism.

like image 195
missingfaktor Avatar answered Sep 18 '22 14:09

missingfaktor