CSC/ECE 517 Fall 2012/ch1 1w31 sa: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
No edit summary
 
(59 intermediate revisions by the same user not shown)
Line 5: Line 5:
This article helps in understanding the concepts of Closures and Methods and also provides a comparison between the two.
This article helps in understanding the concepts of Closures and Methods and also provides a comparison between the two.


 
In [http://en.wikipedia.org/wiki/Type_system#Static_typing Statically typed] languages, methods (also known as procedures or functions) are a set of instructions that perform a specific task. The main objective of methods is to provide reusability of code. Methods can be used to retrieve the state of an object i.e. object’s instance variables. Existence for methods is tied to life time of Objects to which they belong. But many a times there are certain problem domains, where methods are not enough to provide a flexible, elegant implementation and we need the state of a variable to persist even when it is not in the scope of currently running method. One such elegant mechanism which comes out handy in situations as such is Closure.
In Statically typed languages, methods (also known as procedures or functions) are a set of instructions that perform a specific task. The main objective of methods is to provide reusability of code. Methods can be used to retrieve the state of an object i.e. object’s instance variables. Existence for methods is tied to life time of Objects to which they belong. But many a times there are certain problem domains, where methods are not enough to provide a flexible, elegant implementation and we need the state of a variable to persist even when it is not in the scope of currently running method. One such elegant mechanism which comes out handy in situations as such is Closure.
 


Closures are blocks of code that can be passed around like objects, which have the property that they are "bound" to the context (or state of the program) in which they were created and therefore are not dependent on the presence of object or functions which created it.
Closures are blocks of code that can be passed around like objects, which have the property that they are "bound" to the context (or state of the program) in which they were created and therefore are not dependent on the presence of object or functions which created it.


=='''Methods'''==
=='''Methods'''==
A Method is a Subroutine (or Procedure or Function)  in a class that defines the behaviour exhibited by the associated Class instances at runtime. Methods defined within a Class are bound to the class either by Static or Dynamic binding.
A Method is a [http://en.wikipedia.org/wiki/Subroutine Subroutine] (or Procedure or Function)  in a class that defines the behaviour exhibited by the associated Class instances at runtime. Methods defined within a Class are bound to the class either by [http://en.wikipedia.org/wiki/Static_binding Static binding] or [http://en.wikipedia.org/wiki/Dynamic_binding_(computer_science) Dynamic binding].




Line 39: Line 37:


===Different types of methods===
===Different types of methods===
Instance methods
====Instance methods====
Instance methods are the methods which are  bound to objects of the class i.e. there creation depends on creation of object. Instance methods can access instance variables and instance methods directly. Instance methods can also access class variables and class methods directly.
Instance methods are the methods which are  bound to objects of the class i.e. there creation depends on creation of object. Instance methods can access instance variables and instance methods directly. Instance methods can also access class variables and class methods directly.
Static methods
 
====Static methods====
These are also known as Class methods as they belong to the whole class and not a instances or objects in the class. We need these methods if we don’t want a particular functionality to be dependent on creation of objects.
These are also known as Class methods as they belong to the whole class and not a instances or objects in the class. We need these methods if we don’t want a particular functionality to be dependent on creation of objects.
Class methods can access class variables and class methods directly.
Class methods can access class variables and class methods directly.
Class methods cannot access instance variables or instance methods directly i.e. they must use an object reference. Also, class methods cannot use this keyword as there is no instance for this to refer to.
Class methods cannot access instance variables or instance methods directly i.e. they must use an object reference. Also, class methods cannot use this keyword as there is no instance for this to refer to.
For Ex :-  
 
In Java we have a method public static void main(Strings args[])
For Example:   
This method is where the interpreter starts reading the code and this is a static method because this is the first method that is called when we try to execute the class and at that time there are no objects created.
In Java we have a method public static void main(Strings args[])<ref>http://wiki.answers.com/Q/Public_static_void_main_String_arg_means</ref>. This method is where the [http://en.wikipedia.org/wiki/Interpreter_(computing) interpreter] starts reading the code and this is a static method because this is the first method that is called when we try to execute the class and at that time there are no objects created.
Accessor methods
 
Accessor methods are a instance method with the aim to get or set the value of instance variables. Object oriented languages provide the way to hide the instance variables associated with object to outside world by means of encapsulation i.e. marking the instance variables private. So any object can’t access the instance variables of a class directly, this is where accessor methods come into picture. They are the methods through which an object can access the instance variables and we can define some rules in these methods which should be fulfilled in order to set or get these variables.
====Accessor methods====
Accessor methods are a instance method with the aim to get or set the value of instance variables. Object oriented languages provide the way to hide the instance variables associated with object to outside world by means of [http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) encapsulation] i.e. marking the instance variables private. So any object can’t access the instance variables of a class directly, this is where accessor methods come into picture. They are the methods through which an object can access the instance variables and we can define some rules in these methods which should be fulfilled in order to set or get these variables.
 
 
Example: In following Java class weight is an instance variable and is marked private so that any object can’t directly set its value to some incorrect state. Like weight can’t be negative.
Example: In following Java class weight is an instance variable and is marked private so that any object can’t directly set its value to some incorrect state. Like weight can’t be negative.
  Class Person
  Class Person
Line 70: Line 72:
  }
  }


=='''Closures'''==
=='''Closures<ref>http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/</ref>'''==
A closure is a computer science concept which can be seen in different web programming languages such as JavaScript, Ruby, ActionScript 3.0 and newer versions of PHP.
A closure is a computer science concept which can be seen in different web programming languages such as JavaScript<ref>http://www.oreillynet.com/onjava/blog/2006/08/will_we_have_closures_in_java.html</ref>, Ruby, ActionScript 3.0 and newer versions of PHP.
 


A closure is basically a method/function that has the following two properties:
A closure is basically a method/function that has the following two properties:
*We can pass it around like an object (to be called later)
*We can pass it around like an object (to be called later)
*It remembers the values of all the variables that were in scope when the function was created. It is then able to access those variables when it is called even though they may no longer be in scope.
*It remembers the values of all the variables that were in scope<ref>http://en.wikipedia.org/wiki/Scope_(computer_science)</ref> when the function was created. It is then able to access those variables when it is called even though they may no longer be in scope.


 
Closures must be explicitly supported by the language. In order for the language to be able to support closures, it must support [http://en.wikipedia.org/wiki/First-class_function first-class functions].
Closures must be explicitly supported by the language. In order for the language to be able to support closures, it must support first-class functions.


===Comparison with methods===
===Comparison with methods===
A normal function is defined in a particular scope (i.e. in a class) and can only be called within that scope. This function has access to all the variables in the scope that it is defined, like the parameters that are passed into it as well as class variables.
A normal function is defined in a particular scope (i.e. in a class) and can only be called within that scope. This function has access to all the variables in the scope that it is defined, like the parameters that are passed into it as well as class variables.


 
A closure on the other hand may be defined in one scope and be called in a completely different scope (since we can pass it around before calling it). Because of this, when a closure is created, it retains the values of all the variables that were in scope when the closure was defined. Even if the variables are generally no longer in scope when the closure is called, within the closure they still are. In other words, the closure retains knowledge of its [http://www.ai.mit.edu/projects/iiip/doc/CommonLISP/HyperSpec/Body/sec_3-1-1-3.html lexical environment] at the time it was defined.
A closure on the other hand may be defined in one scope and be called in a completely different scope (since we can pass it around before calling it). Because of this, when a closure is created, it retains the values of all the variables that were in scope when the closure was defined. Even if the variables are generally no longer in scope when the closure is called, within the closure they still are. In other words, the closure retains knowledge of its lexical environment at the time it was defined.


===Examples===
===Examples===
====A Simple Example of a Closure====
====A Simple Example of a Closure====
   
   
  4.times {puts "Inside the times method."}
  4.times {puts "This is printed four times."}
   
   
   
   
  Output:
  Output:
  Inside the times method.
  This is printed four times.
  Inside the times method.
  This is printed four times.
  Inside the times method.
  This is printed four times.
  Inside the times method.
  This is printed four times.


Here, times is a method on the 4 object. It executes the code in the closure four times. {puts "Inside the times method."} is the closure. It is an anonymous function that is passed into the times method and prints a static sentence. This code is simpler than the alternative with a for loop, shown in the next example.
Here, times is a method on the 4 object. It executes the code in the closure four times. {puts "This is printed four times."} is the closure. It is an anonymous function that is passed into the times method and prints a static sentence. This code is simpler than the alternative with a for loop, shown in the next example.


====Looping without closures====
====Looping without closures====
  for i in 1..4
  for i in 1..4
     puts "Inside the times method."
     puts "This is printed four times."
  end
  end


Argument list is the first extension that Ruby adds to the simple code block . A method or function can communicate with a closure by passing in arguments. In Ruby, we represent the arguments with a comma-separated list of arguments, between ||characters, such as |argument, list|. Using arguments in this way, we can easily build iteration into data structures such as arrays.
Argument list is the first extension that Ruby adds to the simple code block . A method or function can communicate with a closure by passing in arguments. In Ruby, we represent the arguments with a comma-separated list of arguments, between ||characters, such as |argument, list|. Using arguments in this way, we can easily build iteration into data structures such as arrays.


===Using closures with collections===
====Using closures with collections====
  ['red', 'green', 'blues'].each {|item| puts item}
  ['red', 'green', 'blues'].each {|item| puts item}
   
   
Line 128: Line 127:


===Advantages of Closures===
===Advantages of Closures===
Closures are very useful for making code more clear and readable, which eventually is easier to debug and contains fewer bugs. Closures are extremely useful for implementing call-backs in event driven systems. Closures can be used to define control structures. Designers of software libraries can allow users to customize behaviour by passing closures as arguments to important functions. For example, a multiple generator function can generate any multiple as required by user for a number as shown below:


 
def  create_multiplier
 
    lambda do |n|
 
        n *m
 
    end
=='''Instance methods'''==
The object of a class receives a method name to be executed, the following steps are carried out for matching and executing the method:
 
*First, the object looks in its own [http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html instance methods].
*Second, it looks in the list of instance methods that all objects of that class share.
*Third, in each of the included [http://www.tutorialspoint.com/ruby/ruby_modules.html modules] of that class, in reverse order of inclusion.
*Fourth, it looks in that class’s superclass.
*Fifth, in the superclass’s included modules, all the way up until it reaches the class Object.
*Sixth, if it still can’t find a method, the very last place it looks is in the [http://linux.die.net/lkmpg/x40.html Kernel module], included in the class Object.
*Finally, it calls method_missing (if defined in the class), else throws up the NOMethodError exception.
 
This entire tracing that the object does is the method lookup path.
 
=='''Examples'''==
===Calling defined and undefined methods===
 
class A // creating a class 'A'
def say // defining a method 'say'
puts " say Hi " // body of method say
  end
  end
end
Creating the object of the class
   
   
  a=A.new       // object of the class
doubler = create_multiplier(2)
  => #<A:0x2a082e0>    //object id
tripler = create_multiplier(3)
 
  quad = create_multiplier(4)
Calling the defined method
 
a.say                  // defined method
  => say Hi       // returned result
 
Calling the undefined method
   
   
  a.sayhi                // undefined method sayhi
  puts doubler[5] # 10
  NoMethodError: undefined method `sayhi' for #<A:0x2a082e0>  // the NoMethodError is raised
puts tripler[10]    # 30
  puts quad[15] # 60


===method_missing implementation<ref>http://www.thirdbit.net/articles/2007/08/01/10-things-you-should-know-about-method_missing/</ref>===
===Blocks<ref>http://www.elonflegenheimer.com/2012/05/26/what-i-like-about-ruby.html#blocks</ref>===
Blocks are the most commonly used form of closures in Ruby. We can find them all over the core Ruby libraries. They are nameless functions and can be passed anywhere. Blocks can be visualized as just a chunk of code that will be yielded to or called in the method we supply it to.
Blocks are defined after the last parameter to a method call between {} or do/end. Each call to yield in the method will invoke the block that was passed to that method. We can specify arguments to yield that will be passed to the block. If we do this, we must also specify the same parameters in the block definition. Each method can only receive a single block argument; although, it may yield to this single block multiple times. Calling yield without supplying a block will result in an error.


class A
A simple example:
  def say
  arr = [1,2,3,4]
puts " say hi "
  arr.each do |bl|
end
  puts bl
def method_missing(m,*args,&block) // defining method_missing
  puts " This method does not exist" // body of method_missing
  end
  end
  end
Calling a method that is not defined
   
   
  a=A.new
  Output:
  a.sayhi                                // calling the undefined method sayhi with no arguments
  1
  => This method does not exist // this result returned when method_missing is executed
  2
 
3
When the object 'a' traces its method lookup path for a matching method as 'sayhi', upon failure it resorts to method_missing and the body of method_missing is executed. 'method_missing' is the last resort.
4
 
 
Sometimes when a class has many methods that do generally the same kinds of things, and the programmer is not sure in advance which methods the user will call since there are so many of them, and they are all so similar, implementing all of them by hand seems futile. In these situations method_missing makes a new method that was previously not defined and adds it to the class. The below 'Generic Handler' example implements this.


===passing parameters to an undefined method call===
===Procs<ref>http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/</ref>===
Procs are nameless block of code that can be represented as an object and can be passed around or called at will. A Proc is a closure and an object that can be bound to a variable and reused. Procs are defined by calling Proc.new or proc followed by a block. It can also be created by calling the #to_proc method of a Method, Proc, or Symbol. A Proc can be invoked through its #call method.


  class A
  p = Proc.new do
def add(a,b)
    puts 'Hello!'
a+b
end
def method_missing(name,*args,&block)    // the method_missing is defined and the *args parameter accepts all the parameters passed during                                
                                            the method call 
puts “You have typed the method name wrong and these were the parameters passed ; #{args[0]}, #{args[1]}”
end                       
  end
  end
The passed parameters are stored in the array 'args' and can be accessed like a normal array               
                                                 
   
   
Calling the defined method
p.call
 
  p.call
  a.add(1,2)         // calling the defined method add and passing the parameters (1,2)
  p.call
  => 3                          // result
 
Calling the undefined method
   
   
  a.adds(4,2) // calling the undefined method adds and passing the parameter (4,2)
  Output:
  => You have typed the method name wrong and these were the parameters passed; 4, 2
  Hello!
Hello!
Hello!


The user made a genuine mistake by typing 'adds', but this method is not defined. When the 'adds' method with parameters is called, the object 'a' tries to match the method in the method lookup path. Upon failure it invokes method_missing, the args are passed, stored in the array 'args' and the body of method_missing is executed.
We created a proc which held the block of code, and then we called the proc three times.


===converting numbers from roman representation to integer representation<ref>http://www.rubyquiz.com/quiz22.html</ref>===
The main difference between a block and a proc is that, we can only pass a single block to a method but we can pass multiple procs around because procs are regular objects.<ref>http://www.skorks.com/2010/05/ruby-procs-and-lambdas-and-the-difference-between-them/</ref>
class Roman
@@Roman_to_Numeric = {'i' => 1, 'v' => 5, 'x' => 10, 'l' => 50, 'c' => 100, 'd' => 500, 'm' => 1000} 
def method_missing(method_var,*args,&block)
numeric_value = 0
roman_string = method_var.to_s.downcase
for i in 0...roman_string.length-1
if (cond) == nil
else
puts "Roman string is invalid"
return
end
end
while roman_string != ""
if roman_string[roman_string.length - 1] == 'x' && roman_string[roman_string.length - 2] == 'i'
numeric_value += 9
roman_string.chop!
roman_string.chop!
elsif
roman_string[roman_string.length - 1] == 'v' && roman_string[roman_string.length - 2] == 'i'
numeric_value += 4
roman_string.chop!
roman_string.chop!
else
numeric_value += @@Roman_to_Numeric[roman_string[(roman_string.length)-1]]
roman_string.chop!
end
end
puts "Numeric Value for #{method_var} is: #{numeric_value}"
end
end
'''cond''' = '''['''@@Roman_to_Numeric[roman_string[i]]-@@Roman_to_Numeric[roman_string[i+1]] == 0 || @@Roman_to_Numeric[roman_string[i]]-@@Roman _ to_                              Numeric [ roman _ string [ i + 1 ] ]  ==  - 9 || @@Roman_to_Numeric[roman_string[i]]-@@Roman_to_Numeric[roman_string[i+1]] == -4    ||    @@Roman_to_Numeric[roman_string[i]]-@@Roman_to_Numeric[roman_string[i+1]] >= 4) && (/.v.x/ =~ roman_string''']'''


===Lambdas===
Lambdas are a more strict form of Proc. They are defined with lambda or ->(). The differences between a lambda and a proc are:
*Lambdas are more strict with regard to argument checking.<ref>http://stackoverflow.com/questions/911349/argument-checking-problem-in-bash-script</ref>
*Lambdas can return a value with the return keyword.


Calling the undefined methods
1 a = ->(x,y) {x+y}
2 a.call 2,3
3 => 5


r= Roman.new
=='''Conclusion'''==
r.vii
r.iClx
r.xxix
r.xxxi
r.xxiv
r.xxvi
r.vx


The Output
Closures are more convenient to use than traditional methods and they provide better encapsulation of private information. This doesn't necessarily mean that closures should be added to languages that don't fully support them. However there is a good place for them in [http://en.wikipedia.org/wiki/Dynamic_programming_language dynamic languages] such as Ruby and [http://en.wikipedia.org/wiki/JavaScript JavaScript], as well extensions of static languages such as Groovy.<ref>http://groovy.codehaus.org/Closures</ref>


Numeric Value for vii is: 7
=='''References'''==
Roman string is invalid
<references/>
Numeric Value for xxix is: 29
Numeric Value for xxxi is: 31
Numeric Value for xxiv is: 24
Numeric Value for xxvi is: 26
Roman string is invalid


===method_missing to log method calls<ref>http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2007/wiki1b_2_22</ref>===
=='''Further Suggested Reading'''==
Another application that makes use of method_missing could be a simple logger used for debugging purposes. Many times, it may be required to log the trace of called methods and provide information such as: called method-name, arguments, return type. It can be tedious to repeat this part of code in every method. A simple solution to this problem can be obtained using method_missing as:
[http://weblog.raganwald.com/2007/01/closures-and-higher-order-functions.html 1. Reg Braithwaite-Closures and Higher-Order Functions]
 
  class SimpleCallLogger
  def initialize(o)
  @obj = o
  end
  def method_missing(methodname, *args)
  puts "called: #{methodname}(#{args})"
  a = @obj.send(methodname, *args)
  puts "\t-> returned: #{a}"
  return a
  end
  end


This program makes use of method_missing in a way that it wraps around called method to output the logging information on entry and on exit, it logs the return type. Further, method_missing intercepts the method call and forward it to internal object with ‘send’ method of ruby. Hence, this use of method_missing acts as wrapper.
[http://www.artima.com/intv/closures.html 2. Blocks and Closures in Ruby- A Conversation with Yukihiro Matsumoto]


===Generic Handler===
[http://csharpindepth.com/Articles/Chapter5/Closures.aspx 3. The Beauty of Closures]
class NoBar
def method_missing(methodname, *args)
define_method(:bar) if "bar" == methodname.to_s
define_method(:nobar) if "nobar" == methodname.to_s
end
end


This is an example of using method_missing as a generic handler to handle when a calling method is not exist. You can use missing_method to dynamically create a method at a runtime.
[http://innig.net/software/ruby/closures-in-ruby.rb 4. Closures in Ruby ''Paul Cantrell'']


=='''Advantages of method_missing'''==
[http://www.ibm.com/developerworks/java/library/j-cb01097/index.html 5. IBM Developerworks - Crossing borders : Closures]


*In addition to specifying the error messages for the undefined methods, method_missing provides a more dynamic behavior in the programming environment.
[http://gafter.blogspot.com/2007/01/definition-of-closures.html 6. A Definition of closures ''by Neal Gafter'']
*If we are unfamiliar with the usage of the objects we created, then using method_missing is a good technique.
*Handles problems at runtime.
*Define's a generic method_missing and handle's any undefined method, a big advantage over Java. In Java, when you call an undefined method, the program will not compile.
*method_missing falls under the general technique of [http://en.wikipedia.org/wiki/Metaprogramming meta-programming]. Employ meta-programming in missing_function to write an another function to handle the call.


=='''Disadvantages of method_missing'''==
[http://stackoverflow.com/questions/1305570/closures-why-are-they-so-useful 7. Closures - Why are they so useful]
*Slower than conventional method lookup. Simple tests indicate that method dispatch with method_missing is at least two to three times as expensive in time as conventional dispatch.


*Since the methods being called never actually exist—they are just intercepted at the last step of the method lookup process—they cannot be documented or introspected as conventional methods can.
[http://programmers.stackexchange.com/questions/42193/what-are-the-benefits-of-closure-primarily-for-php 8. Benefits of closures]


*[http://blog.jayfields.com/2008/02/ruby-dynamically-define-method.html Dynamic methods] must go through the method_missing method, the body of that method can become quite large if there are many different aspects of the code that needs to add methods dynamically.
[http://ynniv.com/blog/2007/08/closures-in-python.html 9. Closures in Python]


*method_missing restricts compatibility with future versions of an [http://en.wikipedia.org/wiki/Application_programming_interface API]. Introducing new methods in a future API version can break users' expectations.
[http://howtonode.org/why-use-closure 10. Why Use "closure"? ''by Tim Caswell'']


=='''Key Points'''==
[http://rickyclarkson.blogspot.com/2007/10/why-java-needs-closures-it-already-has.html 11. Ricky's Technical Blog; Why Java Needs Closures (It Already Has Them)]
*Ruby knows method_missing( ) exisits, because it's a private instance method of 'BasicObject' that every object inherits. The BasicObject#method_missing( ) responds by raising the NoMethodError. Overriding this method_missing( ) allows you to call methods that don't really exist.


*If method_missing is only looking for certain method names, don't forget to call the [http://en.wikibooks.org/wiki/Java_Programming/Keywords/super super] keyword if you haven't found what you're looking for, so that the other superclass' method_missing can handle it.
[http://soft.vub.ac.be/amop/at/tutorial/multiparadigm 12. On Scoping, Closures, Methods and Messages]


*[http://www.prateekdayal.net/2007/10/16/rubys-responds_to-for-checking-if-a-method-exists/ obj.respond_to?] function returns 'true' if the obj responds to the given method. So if you want to know whether your class will respond to a function you can use respond_to? to know the answer. But if method_missing() is used, the output may not be what you expect.
[http://en.wikipedia.org/wiki/Abstract_factory_pattern 13. Abstract Factory Pattern]


*Below class A defines only method method_missing() and no other method. When a new object of class A tries to access a method say 'foo', the respond_to? will return the value 'false'. When you actually try to implement it using “a.foo”, the code will get executed, courtesy of method_missing(). Even though the respond_to? says that you cannot access 'foo' method using object of class A, if you have method_missing() defined, you can access the method.
[http://c2.com/cgi/wiki?ScopeAndClosures 14. Cunningham & Cunningham, Inc.; Scope and Closures]


class A
[http://www.quora.com/Computer-Programming/What-are-the-disadvantages-of-closures 15. Disadvantages of closures]
def method_missing(method_id)
puts "In method_missing"
end
end
 
a = A.new
puts a.respond_to?(:foo)
a.foo
 
Output
false
In method_missing
 
*If within method_missing() we define an undefined method.
 
class A
@@i = 0
def method_missing(method_id)
puts "In Method Missing #{@@i}"
@@i += 1
self.fun
end
end
 
a = A.new
puts a.respond_to?(:foo) // just checking whether the receiver 'a' responds to the method 'foo'
 
a.foo
 
Output
 
The expected result would be a 'stack level too deep' error.
 
When the 'foo' method is called, after no method match the method_missing is run and this block has a method “self.fun” that is undefined. Here when the program execution encounters 'self.fun' it once again calls method_missing. This goes on in an endless loop till the stack memory is full.
 
=='''References'''==
<references/>
 
=='''Further Suggested Reading'''==
*http://www.rubyinside.com/
*http://blog.jayfields.com/2008/02/ruby-replace-methodmissing-with-dynamic.html
*http://liquiddevelopment.blogspot.com/2006/04/twisting-and-shaping-dsls-using-ruby.html
*http://blog.rubybestpractices.com/posts/gregory/031-issue-2-method-lookup.html
*http://phrogz.net/RubyLibs/RubyMethodLookupFlow.pdf

Latest revision as of 21:38, 19 September 2012

Closures and Methods:


Introduction

This article helps in understanding the concepts of Closures and Methods and also provides a comparison between the two.

In Statically typed languages, methods (also known as procedures or functions) are a set of instructions that perform a specific task. The main objective of methods is to provide reusability of code. Methods can be used to retrieve the state of an object i.e. object’s instance variables. Existence for methods is tied to life time of Objects to which they belong. But many a times there are certain problem domains, where methods are not enough to provide a flexible, elegant implementation and we need the state of a variable to persist even when it is not in the scope of currently running method. One such elegant mechanism which comes out handy in situations as such is Closure.

Closures are blocks of code that can be passed around like objects, which have the property that they are "bound" to the context (or state of the program) in which they were created and therefore are not dependent on the presence of object or functions which created it.

Methods

A Method is a Subroutine (or Procedure or Function) in a class that defines the behaviour exhibited by the associated Class instances at runtime. Methods defined within a Class are bound to the class either by Static binding or Dynamic binding.


Following is a Ruby example that shows how methods can be used to statically bind to the state of an object:

class Account
 def initialize(default)
   @balance = default
 end
 
 def get_balance
   @balance
 end
 
 def set_balance(value)
   @balance = value
 end
end

account1 = Account.new(100)
puts account1.get_balance  #prints 100
account1.set_balance(200)
puts account1.get_balance  #prints 200

Here the methods are statically bound to the object account1 and have access to its state as long as this object is in existence.

Different types of methods

Instance methods

Instance methods are the methods which are bound to objects of the class i.e. there creation depends on creation of object. Instance methods can access instance variables and instance methods directly. Instance methods can also access class variables and class methods directly.

Static methods

These are also known as Class methods as they belong to the whole class and not a instances or objects in the class. We need these methods if we don’t want a particular functionality to be dependent on creation of objects. Class methods can access class variables and class methods directly. Class methods cannot access instance variables or instance methods directly i.e. they must use an object reference. Also, class methods cannot use this keyword as there is no instance for this to refer to.

For Example: In Java we have a method public static void main(Strings args[])<ref>http://wiki.answers.com/Q/Public_static_void_main_String_arg_means</ref>. This method is where the interpreter starts reading the code and this is a static method because this is the first method that is called when we try to execute the class and at that time there are no objects created.

Accessor methods

Accessor methods are a instance method with the aim to get or set the value of instance variables. Object oriented languages provide the way to hide the instance variables associated with object to outside world by means of encapsulation i.e. marking the instance variables private. So any object can’t access the instance variables of a class directly, this is where accessor methods come into picture. They are the methods through which an object can access the instance variables and we can define some rules in these methods which should be fulfilled in order to set or get these variables.


Example: In following Java class weight is an instance variable and is marked private so that any object can’t directly set its value to some incorrect state. Like weight can’t be negative.

Class Person
{
    private int weight;
    public int getWeight()
    {
    }
    public int setWeight(weight)
    {
        if(weight < 0)
        {
             // Some error
        }
        else
        {
             this.weight = weight;
        }
    }
}

Closures<ref>http://www.skorks.com/2010/05/closures-a-simple-explanation-using-ruby/</ref>

A closure is a computer science concept which can be seen in different web programming languages such as JavaScript<ref>http://www.oreillynet.com/onjava/blog/2006/08/will_we_have_closures_in_java.html</ref>, Ruby, ActionScript 3.0 and newer versions of PHP.

A closure is basically a method/function that has the following two properties:

  • We can pass it around like an object (to be called later)
  • It remembers the values of all the variables that were in scope<ref>http://en.wikipedia.org/wiki/Scope_(computer_science)</ref> when the function was created. It is then able to access those variables when it is called even though they may no longer be in scope.

Closures must be explicitly supported by the language. In order for the language to be able to support closures, it must support first-class functions.

Comparison with methods

A normal function is defined in a particular scope (i.e. in a class) and can only be called within that scope. This function has access to all the variables in the scope that it is defined, like the parameters that are passed into it as well as class variables.

A closure on the other hand may be defined in one scope and be called in a completely different scope (since we can pass it around before calling it). Because of this, when a closure is created, it retains the values of all the variables that were in scope when the closure was defined. Even if the variables are generally no longer in scope when the closure is called, within the closure they still are. In other words, the closure retains knowledge of its lexical environment at the time it was defined.

Examples

A Simple Example of a Closure

4.times {puts "This is printed four times."}


Output:
This is printed four times.
This is printed four times.
This is printed four times.
This is printed four times.

Here, times is a method on the 4 object. It executes the code in the closure four times. {puts "This is printed four times."} is the closure. It is an anonymous function that is passed into the times method and prints a static sentence. This code is simpler than the alternative with a for loop, shown in the next example.

Looping without closures

for i in 1..4
    puts "This is printed four times."
end

Argument list is the first extension that Ruby adds to the simple code block . A method or function can communicate with a closure by passing in arguments. In Ruby, we represent the arguments with a comma-separated list of arguments, between ||characters, such as |argument, list|. Using arguments in this way, we can easily build iteration into data structures such as arrays.

Using closures with collections

['red', 'green', 'blues'].each {|item| puts item}


Output: 
red
green
blue

The each method is just one way to iterate. Often, we want to produce a new collection with the results of an operation. This method in Ruby is called collect. We may also join the contents of an array with some arbitrary string, which is shown in the next example.

Passing arguments to a closure

colours = ['red', 'green', 'blue'].collect {|item| item.upcase}
puts colours.join(" and ") + " nothing."

RED and GREEN and BLUE and nothing.

Here, the first line of code takes each element of an array, calls the closure on it, and then builds a collection with the results. The second concatenates all of the elements into a sentence, with " and " between each one.

Advantages of Closures

Closures are very useful for making code more clear and readable, which eventually is easier to debug and contains fewer bugs. Closures are extremely useful for implementing call-backs in event driven systems. Closures can be used to define control structures. Designers of software libraries can allow users to customize behaviour by passing closures as arguments to important functions. For example, a multiple generator function can generate any multiple as required by user for a number as shown below:

def  create_multiplier
    lambda do |n|
        n *m
    end
end

doubler = create_multiplier(2)
tripler = create_multiplier(3)
quad = create_multiplier(4)

puts doubler[5] # 10
puts tripler[10]    # 30
puts quad[15] # 60 

Blocks<ref>http://www.elonflegenheimer.com/2012/05/26/what-i-like-about-ruby.html#blocks</ref>

Blocks are the most commonly used form of closures in Ruby. We can find them all over the core Ruby libraries. They are nameless functions and can be passed anywhere. Blocks can be visualized as just a chunk of code that will be yielded to or called in the method we supply it to. Blocks are defined after the last parameter to a method call between {} or do/end. Each call to yield in the method will invoke the block that was passed to that method. We can specify arguments to yield that will be passed to the block. If we do this, we must also specify the same parameters in the block definition. Each method can only receive a single block argument; although, it may yield to this single block multiple times. Calling yield without supplying a block will result in an error.

A simple example:

arr = [1,2,3,4]
arr.each do |bl|
puts bl
end

Output:
1
2
3
4

Procs<ref>http://www.robertsosinski.com/2008/12/21/understanding-ruby-blocks-procs-and-lambdas/</ref>

Procs are nameless block of code that can be represented as an object and can be passed around or called at will. A Proc is a closure and an object that can be bound to a variable and reused. Procs are defined by calling Proc.new or proc followed by a block. It can also be created by calling the #to_proc method of a Method, Proc, or Symbol. A Proc can be invoked through its #call method.

p = Proc.new do
    puts 'Hello!'
end

p.call
p.call
p.call

Output:
Hello!
Hello!
Hello!

We created a proc which held the block of code, and then we called the proc three times.

The main difference between a block and a proc is that, we can only pass a single block to a method but we can pass multiple procs around because procs are regular objects.<ref>http://www.skorks.com/2010/05/ruby-procs-and-lambdas-and-the-difference-between-them/</ref>

Lambdas

Lambdas are a more strict form of Proc. They are defined with lambda or ->(). The differences between a lambda and a proc are:

1 a = ->(x,y) {x+y}
2 a.call 2,3
3 => 5

Conclusion

Closures are more convenient to use than traditional methods and they provide better encapsulation of private information. This doesn't necessarily mean that closures should be added to languages that don't fully support them. However there is a good place for them in dynamic languages such as Ruby and JavaScript, as well extensions of static languages such as Groovy.<ref>http://groovy.codehaus.org/Closures</ref>

References

<references/>

Further Suggested Reading

1. Reg Braithwaite-Closures and Higher-Order Functions

2. Blocks and Closures in Ruby- A Conversation with Yukihiro Matsumoto

3. The Beauty of Closures

4. Closures in Ruby Paul Cantrell

5. IBM Developerworks - Crossing borders : Closures

6. A Definition of closures by Neal Gafter

7. Closures - Why are they so useful

8. Benefits of closures

9. Closures in Python

10. Why Use "closure"? by Tim Caswell

11. Ricky's Technical Blog; Why Java Needs Closures (It Already Has Them)

12. On Scoping, Closures, Methods and Messages

13. Abstract Factory Pattern

14. Cunningham & Cunningham, Inc.; Scope and Closures

15. Disadvantages of closures