warpedjavaguy

Imperative by day and functional by night

Java Closures – The Fundamental Benefit


Avoiding redundant code is a basic programming instinct.
 

How many times have you written a piece of code and thought “I wish I could reuse this block of code”? How many times have you refactored existing code to remove redundancies? How many times have you written the same block of code more than once before realising that an abstraction exists? How many times have you extracted such abstractions successfully? How difficult was it to do and how much effort was involved? How constrained were you by the current Java language constructs? These are all questions pertaining to the everyday challenges we face as Java programmers in our struggles to achieve zero code redundancy.

Closures are reusable blocks of code that capture the environment and can be passed around as method arguments for immediate or deferred execution. Why do we need them in Java? There are many reasons for and against, but the fundamental benefit they provide is the facilitation of redundant code avoidance. The current Java closures specification makes a strong point of this in the first paragraph where it states: “they allow one to more easily extract the common parts of two almost-identical pieces of code”.

Closures provide an elegant means of reusing blocks of code and avoiding code duplication without the boilerplate. This is the fundamental benefit that closures bring to Java. All other benefits are derived benefits inherited from this fundamental benefit. In fact, all the needs addressed by the Java closures proposal are all derived benefits.

I know I am just stating the obvious and reiterating my point here, but it is just too easy to overlook this one fundamental benefit and be overwhelmed by all others. Java closures make it easier to eliminate redundant code and avoid it altogether!

Advertisements

Written by warpedjavaguy

June 25, 2008 at 10:32 pm

Posted in java, programming

Tagged with

10 Responses

Subscribe to comments with RSS.

  1. Inner classes with short syntax and write ability to local variables do all this and more. Closures are a poor man’s inner class, see URL.

    Howard Lovatt

    June 26, 2008 at 5:53 pm

  2. You cannot in the current Java language write anonymous inner classes without also writing boilerplate code. This is a necessary redundancy that cannot be eliminated.

    For example, the code snippet below contains boilerplate that is redundant and that you should not have to write.

    new Thread(new Runnable() {
      public void run() {
        System.out.println("Anonymous Inner Class");
      }
    }).start();

    ..whereas closures eliminate the redundant boilerplate required above:

    new Thread({ =>
      System.out.println("Closure")
    }).start();

    As an aside, inner classes are a poor man’s closure because
    they do not capture the enclosing environment in its entirety (that is: they do not capture variable names, the ‘this’ object, the referents of break, continue, return, etc..). Inner classes are definitely not closures. See closure definition.

    WarpedJavaGuy

    June 26, 2008 at 8:22 pm

  3. You did not read what Howard wrote… He said “Inner classes with short syntax”. Like with CICE, the only closures proposal that makes sense this late in the Java cycle.

    Mikael Grev

    June 27, 2008 at 7:25 am

  4. What Howard wrote was “Inner classes with short syntax and write ability to local variables do all this and more”. This is simply not true. The reason CICE makes sense is because it eliminates the boilerplate associated with anonymous inner classes.

    My point in this post is to highlight the primary benefit that closures bring to the Java language. They introduce to Java a language construct that eliminates boilerplate and removes unnecessary redundancy.

    WarpedJavaGuy

    June 27, 2008 at 9:46 am

  5. I am with Mikael. CICE, BGGA, C3S (http://www.artima.com/weblogs/viewpost.jsp?thread=182412), and FCM all give shorter syntax and write to local variables. The examples you have given only show that shorter syntax would be nice. There are serious drawbacks with closures (BGGA and FCM), they introduce a second typing system, they are like an object but not quite, and the meaning of return is changed. To allow the closures ‘to play’ with normal objects they get boxed, but there is no unboxing. This leads to strange behaviour, similar to the strange behaviour when primitives get boxed. Further, because there is no unboxing, other odd behaviour happens. Also closures cannot inherit and can only be boxed into interfaces, not classes. Java is first and foremost an OO language, lets keep it that way and not introduce something else that is not an object and requires boxing.

    Howard Lovatt

    June 28, 2008 at 10:25 am

  6. Your BGGA code example has a bug, and is the exact reason why BGGA closures are likely to be difficult to use in real coding. In case you haven’t figured it out, the println requires a trailing semicolon. Why? Because run() from Runnable returns void. Last-line-no-semicolon return only works if there is a non-void return type. And thats the kind of confusing set of rules we can do without in Java.
    (Disclaimer – I’m co-author of FCM closures)

    Stephen Colebourne

    June 28, 2008 at 10:27 am

  7. Stephen, yes the BGGA semicolon rule got me.

    Clearly then what is most desirable is a closure solution that does not introduce odd behavior and change existing semantics. Is CICE good enough? Is BGGA too drastic? Both C3S and BGGA change the semantics. Does FCM strike the right balance?

    The debate over proposals will continue, but until we have closures in Java, the restructuring of code to eliminate redundancies will continue to result in unnecessary code which is itself redundant.

    WarpedJavaGuy

    June 28, 2008 at 12:35 pm

  8. I think the different rules regarding different forms of returned can be overcome using named returns, as suggested in C3S. Neal Gafter has indicated in a reply to one of my blogs that he is considering named returns for BGGA. The idea of named returns is that return returns from the inner class/closure and if you want to return from the method enclosing the inner class.closure you say [methodName].return [value]opt;

    The FCM proposal suggests that return returns from the closure except when the closure is used in a control structure, when it returns from the enclosing method.

    I think that both named returns and the FCM proposal are superior to what is currently in BGGA, but as I said Neal is thinking of changing BGGA.

    The C3S proposal adds no new semantics, it is just short syntax for inner classes. BGGA and FCM add a new construct the closure that is like an object but can’t inherit, can’t have fields, and its class has only one method. To get it to interact with objects it gets auto-boxed; but it can only be boxed into an interface with one method and once boxed there is no auto-unboxing. This autoboxing effectively introduces a second typing mechanism into Java, structural typing, thus complicating programs.

    Personally I can see no advantage in the closure over the inner class, its less powerful than an object and needs auto-boxing and Java is an OO langage and I don’t think we should go adding further non-objects (primitives already cause problems).

    Howard Lovatt

    June 29, 2008 at 10:16 am

  9. You should feel annoyed by this off topic comment to the same degree as i am by the JavaScript snow.

    JS_WTF

    December 9, 2011 at 6:50 am


Comments are closed.

%d bloggers like this: