views:

213

answers:

4

I was reading Object Oriented Javascript and found the concept of closures. I didn't quite understand why and when it is used. Do other languages like Java also have closures? I basically want to understand how knowing the concept of closures can help me improve my coding.

+3  A: 

A closure is a scoping technique. Java does not have closures.

In javascript you can do something like that following:

var scope = this;

var f = function() {
    scope.somethingOnScope //scope is 'closed in' 
}

if you then do something like pass f to a function, scope is the scope of where it was defined.

hvgotcodes
What would you call it then when you refer to variables declared outside the scope of your anonymous class?
Kirk Woll
@Kirk A "minimal closure".
Tom Hawtin - tackline
I have read it that the closure is a scoping technique. Thanks but i want to understand how it helps with a particular coding scenario.
sushil bharwani
@sushil its useful because it allows you to associate a scope with something (e.g. a function) and then pass that function around.
hvgotcodes
+3  A: 

Closures are know by various names in various languages but the essential points are as follows:

To create closures you need a language where the function type is a 1st class citizen i.e. it can be bound to a variable and passed around like any old string, int or bool.

You also need to be able to declare functions inline. In javascript you can do something like this:

foo("bar", "baz" function(x){alert("x")});

To pass a anonymous function as a parameter to the foo function. We can use this to create a closure.

Closures "close over" variables so can be used to pass scoped variables around. Consider this example:

function foo(){
    var spam = " and eggs";
    return function(food){alert(food + spam)};
}
var sideOfEggs = foo();

The side of eggs now contains a function which appends " and eggs" to whatever foodstuff it is passed. The spam variable is part of the foo function scope and would have been lost when the function exited, except that the closure "closed over" the namespace preserving it as long as the closure remains in memory.

So we're clear on closures having access to their parent's private scoped variables right? So how about using them to simulate private access modifiers in javascript?

var module = (function() {   
    var constant = "I can not be changed";

     return {
         getConstant    :    function() {  //This is the closure
            return constant;               //We're exposing an otherwise hidden variable here
         }
    };
}());                                     //note the function is being defined then called straight away

module.getConstant();                     //returns "I can not be changed"
module.constant = "I change you!";
module.getConstant();                     //still returns "I can not be changed" 

So what's happening here is we're creating and immediately calling an anonymous function. There is one private variable in the function. It returns an object with a single method which references this variable. Once the function has exited the getConstant method is the sole way of accessing the variable. Even if this method is removed or replaced it will not give up it's secret. We have used closures to achieve encapsulation and variable hiding. For a more thorough explanation of this see http://javascript.crockford.com/private.html

Java does not have closures (yet). The closest it has are anonymous inner classes. However to instantiate one of these inline you have to instantiate an entire object (usually from an existing interface).The beauty of closures is they encapsulate simple, expressive statements which is somewhat lost in the noise of anonymous inner classes.

Ollie Edwards
From Wikipedia: "The term closure is often mistakenly used to mean anonymous function. This is probably because most languages implementing anonymous functions allow them to form closures and programmers are usually introduced to both concepts at the same time. These are, however, distinct concepts."
Kirk Woll
@Kirk Woll fair point although it was not my intention to equate the two as identical. I will try to make that a bit clearer.
Ollie Edwards
@Ollie i like your explanation.Can you give a more practical example where it makes perfect sense as to yes using the closure was the perfect way to solve a problem
sushil bharwani
@sushil bharwani sure, see my new section on using closures to simulate private members in javascript
Ollie Edwards
+2  A: 

Closure is a very natural feature that allows free-variables to be captured by their lexical environment.

here's an example in javascript:

function x() {

    var y = "apple";

    return (function() {
         return y;
    });
}

function x returns a function. note that when a function is created variables used in this function are not evaluated like when we return an expression. when the function is created it looks to see what variables are not local to the function (free). It then locates these free variables and ensures they are not garbage collected so that they can be used once the function is actually called.

In order to support this feature you need to have first-class functions which java does not support.

Note this is a way we can have private variables in languages like JavaScript.

Ken Struys
FSVO "very natural". The very question points out that it's arcane to many.
Adriano Varoli Piazza
there are applications where it's really natural. forexample when passing around callback functions, and when you're working in functional languages. Just because it's arcane doesn't mean it's not a good idea. :P
Ken Struys
Oh, I don't question their usefulness, far from it. Just saying that it did take some time to wrap my head around them, for me.
Adriano Varoli Piazza
When you have to explain what's going on and you've programmed in imperative languages for a very long time it can be hard. I've seen novice functional programmers just use them without thinking about it and think "we'll of course that will work".
Ken Struys
+6  A: 

A closure is a first class function with bound variables.

Roughly that means that:

  • You can pass the closure as a parameter to other functions
  • The closure stores the value of some variables from the lexical scope that existed at the time that is was created

Java doesn't have closures, although it's fairly common in Java to simulate them using anonymous inner classes. Here's an example:

import java.util.Arrays;
import java.util.Comparator;

public class StupidComparator { 
    public static void main(String[] args) {
        // this is a value used (bound) by the inner class
        // note that it needs to be "final"
        final int numberToCompareTo=10;

        // this is an inner class that acts like a closure and uses one bound value
        Comparator<Integer> comp=new Comparator<Integer>() {
            public int compare(Integer a, Integer b) {
                int result=0;
                if (a<numberToCompareTo) result=result-1;
                if (b<numberToCompareTo) result=result+1;
                return result;
            }
        };

        Integer[] array=new Integer[] {1,10, 5 , 15, 6 , 20, 21, 3, 7};

        // this is a function call that takes the inner class "closure" as a parameter
        Arrays.sort(array,comp);

        for (int i:array) System.out.println(i);
    }
}
mikera
Thanks mikera, what i know understand is clousure is a function with some variables that can be passed as parameters to other functions. I have two questions wat is a first class function and what do you mean by stores some values from lexical scope. Also i am still not getting a perfect scenario where i would be benifited by using it. Sorry i am very new to it so asking too much
sushil bharwani
First class function means that you can treat the function just as you would any other "object" in the language, i.e. pass it as a parameter, store it in a collection etc. Since an anonymous inner class represents a Java object just like any other object, it is "first class" in Java - you can do anything to it that you could do with any other normal object
mikera
Example of the benefit is given above - you have a generic sorting function (e.g. Arrays.sort(..)) that becomes much more powerful because you can pass any comparison function you like a parameter. e.g. you could sort in reverse order, or by number of digits, or by whether or not the number is a prime etc. This basically gives you an extra layer of abstraction when creating algorithms that can be very powerful. It's worth reading up on "functional programming" if you want to learn more.
mikera
wow .. wonderful explanation...
sushil bharwani