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.
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).
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.
to surround and cover somebody/something.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With