Xebia

Blog Xebia France

J2EE, Agility and SOA

May 10th, 2007
Print this ticket

From closures in Popular dance

Debate around the introduction of closures in language Popular dance rages - with all measure and absence of pedantry which can show our profession on this type of subject. In all likelihood, closures will be one of the functionality headlight of Popular dance 7. Remain to know under which form.
Two schools appeared on subject: the first one, indicated BGGA (of the name of his authors and promoters, Gilad Bracha, Neal Gafter, James Gosling and Peter von der Ahe), offers a relatively complex syntactic extension but allowing to introduce into language all idioms necessary for a support of closures similar to that available in Ruby or Smalltalk: function types, free variables, blocks, etc.; the second indicated by the acronym CICE (for Concise Inner Class Expressions) and supported by Joshua Bloch, Doug Lea and "Crazy Bob " Lee, offers more modestly a simplification of the syntax popular dance with the intention of d sinhiber the usage of Inner Class in loco of closures.
The occasion to make a point here on these two approaches and to bring elucidation, otherwise a stone in work, at least on the terms of debate.

Definition most spread by closures is the following (Neal Gafter gives a review of closures ):

In closure simple percentage has function that captures the bindings of free variable in its lexical context.

Substantially, a closure is a block of code r f ren able, manipulating optionnellement of said variables "free" - free in the sense that they are defined not in the block of code, nor globally, but by the context in which the block is carried out.

A little of code often better than a long speech, here is an example very easy in use of closures in Ruby (Ruby makes an intensive usage of closures, what is probably at the origin of affection that carries it his users). This example is drawn of the article of Martin Fowler at subject [there].

Let us imagine that you want to extract from a list of employees a sub-list understanding only those who are frames. A possible realisation in popular dance is the following:

public static List <employee> managers (List <Employee> employees) {
 Result <Employee> = new ArrayList <employee> List ();
 for (Employee e: employees)
  yew tree (e.isManager) result.add (e);
 return Result;
}

In Ruby, the same function would be suchlike encoded:

def managers (employees)
 return employees.select {|e e.isManager}
end

Method select Ruby's Collection is defined in the class. She takes in parametre a block of code - the closure famous - defined between braces. If the block of code takes arguments, these last are declared between two vertical bars (these are the "free" variables, with which range is defined by context). Method select encapsule the algorithmic: iteration on the collection, execution of the block of code for every element and building of a sub-list containing elements for which the block of code assesses at true.

There is of course in Popular dance a rather similar mechanism, allowed by the usage of anonymous overlapped classes (Anonymous Inner Class, or AIC).
Let us assume that the class List have a method, symmetrically in its counterpart Ruby, select, taking in parametre an interface defined as follows:

Then code popular dance could be spelt as follows:

public static List <employee> managers (List <Employee> employees) {
 return employees.select (
  new Filter <employee> {
   public boolean accept Employee (e) {
    return e.isManager ();
   }
  }
 );
}

AIC is the traditional mishap of closures in popular dance. IPA - INTERNATIONAL PHONETIC ALPHABET of JDK widely use it (think of interfaces Runnable, Comparable, Callable or TimerTask, who give closures in classes Thread or Executor, or else allow to configurer collections). Design Patterns callbacks, factories, predicates or stategies are of natural candidates for this type of building. Spring, especially in his framework of templates, exploits them in very good escient to conceal the tiring character of some IPA - INTERNATIONAL PHONETIC ALPHABET, JDBC especially.

Therefore, the programming by closures, very spread to rubyistes, is practically nonexistent at the programmers' popular dance. The listing above gives a first explanation: the syntax of AIC, verbose incredibly, is liable to discourage the best intentions. Then, the support of AIC in Popular dance as mechanism of closures suffers from strict limitations: once instanci e, AIC is a full object, endowed with a range which is peculiar to it, and partly blind in the context which created it. Consequently, variables or methods are solved in range of this new object.

Let us examine, to illustrate these some Ruby's lines:

i = 1;
1.upto (100) {|num i * = num;}
puts i;

This code allows to show the factorial of 100. Variable i is defined outside the closure and changed in its body. Code equivalent popular dance would not compile (supposing that one similar IPA - INTERNATIONAL PHONETIC ALPHABET is available). Indeed, so that an external variable is achieved in the body of AIC, she must be declared final (the underlying reason is that variable is copied in the context of AIC). She cannot therefore be changed. It does not put down difficulty if variable is of a variable type (as a list or a wrapper), but can turn out to be problematic if it is about an immutable type or about one worth portrays (especially G-string and primary types).

Here is a quintessence of the necessary contortions in popular dance to by-pass this pressure:

final int [] numCompares = new int [1];
Arrays.sort (has, new Comparator <Integer> () {
 public int compares (Integer i1, Integer i2) {
  numCompares [0] ++;
  return i1.compareTo (I2);
 }
});
System.out.println (numCompares [0]);

It is on this primordial official report that proposal CICE came into the world. Its object is not to corrupt language popular dance but to return more concise the syntax of creation of AIC (in fact, a subset of these last, called single-abstract-method-types or SAM, which are substantially interfaces including only an only method).

With the syntax offered by CICE, our initial example would be suchlike rewritten:

public static List <employee> managers (List <Employee> employees) {
 return employees.select (
  Filter <Employee> {return element.isManager ();}
 );
}

This concise said syntax is supplemented by an impairment of the rules of access to the local variables of the calling block (especially, those declared expressly public can be allocated in the body of AIC).

This approach has of course the merit of simplicity since ellle introduces no new concept and does not require the existent rewriting of the IPA - INTERNATIONAL PHONETIC ALPHABET; she could moreover be implemented probably with the aid of a modification minor of the compiler.

For some, however, approach CICE is only touching subject lightly and offers only a minimalist provision of closures in Popular dance.

Indeed, generally, AIC breaks the context of execution of calling code and does not allow to keep the semantics of a significant number of syntactic structures (those that Neal Gafter calls " lexically scoped language constructs "):

  • names of variables
  • names of methods
  • names of types
  • signification of this
  • names of quality-labels
  • referent of an education break without quality-label
  • referent of an education continue without quality-label
  • checked exceptions declared or intercepted
  • referent of an education return
  • and some others more exotic (state of allocation of variables, reachability, )

Proposal BGGA is an extension of language popular dance allowing the implementation of closures without break of transparency. The syntax offered by BGGA is far from being coarse, what is worth it many criticisms his denigrators are incidentally often the supporters of CICE.

Without entering the detail (who can be consulted on the site http://www.javac.info/), following characteristics will be kept:

  • BGGA defines a syntax allowing to declare literal resembling closures in this:
    {int x, int y> x+y}

  • BGGA also defines the concept of function portray, in whom a function has a list of arguments, a type back and a clause throws; it is possible to instancier a function portray with the aid of a compatible literal closure
  • transparency lexical is completely guaranteed, both for the association of variables and for the resolution of names or structures of control (break, continue, return) some people closures can however be marked restricted and act in an identical way in AIC
  • BGGA offers a simplified grammar allowing to exploit closures according to a syntax very close to that of structures of control native of language with such syntax, the modification of language to introduce the second form of curl for would have been superfluous

With BGGA, following algorithm

lock.lock ();
try {
 ++ counter;
}
finally {
 lock.unlock ();
}

would become

withLock (lock, {=>
 ++ counter;
});

in canonical form and, in simplified form:

withLock (Lock) {
 ++ counter;
}

Our initial example could be suchlike encoded (if the IPA - INTERNATIONAL PHONETIC ALPHABET of Collection popular dance acquires a method select appropriate):

public static List <employee> managers (List <Employee> employees) {
 return employees.select ({Employee e => e.isManager ()});
}

As recalled higher, the medal has a back. If side client the use of closures BGGA seems relatively simple, the syntax risks of considerably complexifier IPA - INTERNATIONAL PHONETIC ALPHABET of JDK or of frameworks eager to take advantage of it. To give an idea, here is the code of the withLock function used higher:

public static <T, throws E extends Exception>
T withLock (lock lock, {=> T throws E} block) throws E {
 lock.lock ();
 try {
  return block.invoke ();
 } finally {
  lock.unlock ();
 }
}

Following the example of the generic, who returned almost unreadable in the common the source code of some classes of JDK, such syntactic evolution risks raising an additional barrier to the training of language popular dance, and digging the ditch even more between the user of IPA - INTERNATIONAL PHONETIC ALPHABET (Joe Java, as say certain) and the concepteur of IPA - INTERNATIONAL PHONETIC ALPHABET. Is the game worth the candle?

References (all in English):
[1] The proposal BGGA, introduced by Neal Gafter to GOOGLE TechTalks
[2]
[3] A very interesting exchange on the site of Crazy Bob, supporter of CICE
[4] Two articles appeared on developerWorks, first on closures in general, and second more specifically on debate BGGA vs CICE.
[5] A more ancient article, on the traditional approach of closures in popular dance Key words :, , Popular dance

You can follow answers accepted by this article thanks to the thread of comments.

9 answers to closures in Popular dance

  • On May 10th, 2007 in 10:09 (), arnaud said :

    "generic, who were productive almost unreadable to the common"
    You should not go too far.
    The generic are a wholesale trade more. This really missed.
    In more this integrates rather simply with code existent popular dance.

  • On May 10th, 2007 in 13:53 (), Guillaume Bodet said :

    I am also a fan of the generic... Simply, I can only note that their introduction (and in spite of their very good design and their very good integration in IPA - INTERNATIONAL PHONETIC ALPHABET existent) augmented the cost of training of language. And created a distance between the users of IPA - INTERNATIONAL PHONETIC ALPHABET, who can benefit very simply from generic:

    List<String> l = new ArrayList<String>();

    and the creators of IPA - INTERNATIONAL PHONETIC ALPHABET, who control the subtleties of the syntax and of wildcards to write this type of code (extracted of java.util.Collections) :


    public static <T extends Comparable<? super T>> void sort(List<T> list) {
      ...
    }

  • On May 12th, 2007 in 10:51 (), Yann said :

    A big advantage of Popular dance domiciles in its pedagogic coherence and its legibility. Remember, the gun-layers and other malloc, efficient to manage memory, but so not much developer-friendly!
    Objectives? Reduced curve of training, improvement of the maintenabilit ...

    I agree to say that Generiques missed: (cast) with a vengeance is not in the philosophy of simplicity searched by Popular dance. On the other hand, generated code becomes more and more unreadable and harms aforementioned objectives.

    The introduction of closures parried me an error: yes, it reduces the number of lines of code. No, it does not simplify legibility. No, it does not favour Popular dance.

    I think that closures is only a sign of weakness of Popular dance which succumbs to the lobbying of the supporters of Ruby or of the tools of Scripting which allow to encode often in less than lines but to the detriment of legibility, of simplicity.

    Unless wanting to search the addition of a new rubric in our documents of norms of development: "Functionality Popular dance not to be used: closures,"?

    Yann

  • On December 10th, 2007 in 1:46 (), Frank marshal said :

    Guillaume: I think that game is worth the candle, there are the basic users and the advanced users. The same is true with the framework of collections of Sun, I note that the most popular collection is "List" while sometimes a "Jeu" would be more appropriate. Why? I suspect relating complexity of redefining "HashCode" and "Equals" to be at origin (there at least partly, times origin is more worrying). Finally Sun would have been able to content itself with pictures and with the utilitarian class "Collections " (dedicated to pictures in that case), but fortunately that Sun could resist and publish this framework.

    Yann: the code Popular dance produced by the programmer did not wait for the generic to be unreadable, it will be also with closures there; it is the programmer who returns an unreadable code.

    A "Google Tech Talk" given by Neal Gafter on closures: http://www.youtube.com/watch?v=0zVizaCOhME

  • On December 31st, 2007 in 15:24 (), Review of the papers Xebia by J2EE, Agility and SOA :  The blog of Xebia France said :

    [] who continues making debate closures is, about whom we had spoken in this previous ticket. In this article Closures and Preserving the Feel of Popular dance, InfoQ returns on intervention [...]

  • On February 28th, 2008 in 13:49 (), Laurent Des challiers: " Tech " Blog [Wakefulness> Dev] closures in Java7 said :

    [] Xebia: closure in Popular dance [...]

  • On May 26th, 2008 in 18:14 (), Blog Xebia France - Review of the papers Xebia said :

    [] advice on the simplicity of code, its opinion on languages of Scripting and appearance of closures in Popular dance 7, and recommends a list of books which it has particularly [...]

  • On April 29th, 2009 in 16:56 (), Arnault Bonafos said :

    I do not understand, if they want to introduce closure into Popular dance why not to make simply what already makes language Lisp?

  • April 29th, 2009 in 22:27 (), said :

    Good night Arnault,
    By the fact that '{', it is distinctly more cool than '(' :)

    Joke put to one side, this article in summer written in 2007, at present closures was descop es of Popular dance 7. (For lack of having found a consensus on their realisation). They are on the other hand available in GROOVY.

Leave a comment


Defence Colis e - 10/12, avenue of The Ark
92419 Courbevoie Cedex

T l : +33 (0) 1 46 91 76 16
Fax : +33 (0) 1 46 91 88 00
E-mail : info@xebia.fr