Opinion: Closures in Java

Discussions

News: Opinion: Closures in Java

  1. Opinion: Closures in Java (20 messages)

    Bob Lee has been playing with Ruby, and misses their closure support when he works in the Java world. He talks about how he missed it enough to use a simple pattern to enable him to use closures from his Java code. Bob shows the pattern, and usage, and others bring up Closure support from other angles.

    The Jakarta Collections guys have their own closures, and I am sure there are many more (especially since it is implemented as a simple command pattern).

    I have always missed closures myself (as well as delegates, ...). Will we get them in Java at some point? Would they be good to have?

    Read Bob Lee on his Iterating Closure design pattern.

    Also visit the Jakarta docs on Closure.

    Threaded Messages (20)

  2. Check out Groovy[ Go to top ]

    Groovy is a great example of how to improve upon Java without giving up JVM compatibility. It brings a lot of the power of dynamic languages like Smalltalk and makes them easily usable by the masses.

    http://groovy.codehaus.org/

    Cheers,
    Graham
  3. Look at Groovy[ Go to top ]

    Look at Groovy: http://groovy.codehaus.org
  4. Re: Look at Groovy[ Go to top ]

    There are times for strongly typed languages, and there are times for scripting languages. I'm a fan of both under the right circumstances.
  5. Re: Look at Groovy[ Go to top ]

    There are times for strongly typed languages, and there are times for scripting languages. I'm a fan of both under the right circumstances.


    Groovy can be dynamically and statically typed, so you can choose when to be strongly typed inside the same language :)

    [1, 2, 3].each { println(it) }

    or

    List list = [1, 2, 3]
    list.each { Number n | println(n.intValue()) }

    etc

    James
    Core Developers Network
  6. never seen that before[ Go to top ]

    this warrents a post? come on, you people are gone.

    Next you will start calling exceptions "structured continuations" or how about writing a paper on the "method dispatching" and describe how inheritence works... You people are gone.
  7. never seen that before[ Go to top ]

    I agree. Bob Lee appartently has too much time on his hands.
  8. never seen that before[ Go to top ]

    I think Dion tends to be a little "buzzword" happy. Yesterday it was AOP this, Interceptor that-- today its Closures. (b/c everybody know that all the k00l kids are learning Ruby, and want to be Smalltalkers like their dads) Dion, curb your enthusiasm.
  9. Opinion: Closures in Java[ Go to top ]

    Why someone would prefer Groovy to Java or C#, at least it looks weird to me. I don’t even mention performance that would definitely be an issue in the language like this?
  10. Opinion: Closures in Java[ Go to top ]

    Why someone would prefer Groovy to Java or C#, at least it looks weird to me. I don’t even mention performance that would definitely be an issue in the language like this?


    If you're using static typing and not using autoboxing then there's no reason why Groovy performance wouldn't eventually be identical to Java (since it'd be pretty much equivalent bytecode under the covers).

    Sure the use of dynamic method dispatch when using dynamic typing has an overhead - however through judicious use of bytecode generation, we should be able to make that super fast, rather like cglib outperforms reflection via bytecode generation.

    Though right now dynamic method dispatching in Groovy is quite a bit slower than static dispatching in Java - we've not tuned Groovy too much yet (its only just reached first beta :). So please be a little patient on the performance front.

    James
    Core Developers Network
  11. Simpler?[ Go to top ]

    I'm sorry, but after reading the article half a dozen times I still don't get it. Normally, I blame myself but in this case I just have to ask: in what way (or in what circumstances) is this pattern indeed simpler than the vanilla iteration? I seems so over the top, really.
  12. Simpler?[ Go to top ]

    I'm sorry, but after reading the article half a dozen times I still don't get it. Normally, I blame myself but in this case I just have to ask: in what way (or in what circumstances) is this pattern indeed simpler than the vanilla iteration? I seems so over the top, really.



    How about this - iterating over some SQL (and creating some XML markup from it) without having to worry about creating & closing ResultSet, Statement and Connection objects...

    http://groovy.codehaus.org/sql.html

    (The example is near the end of the page)

    James
    Core Developers Network
  13. Simpler?[ Go to top ]

    I'm sorry, but after reading the article half a dozen times I still don't get it. Normally, I blame myself but in this case I just have to ask: in what way (or in what circumstances) is this pattern indeed simpler than the vanilla iteration? I seems so over the top, really.

    >
    >
    > How about this - iterating over some SQL (and creating some XML markup from it) without having to worry about creating & closing ResultSet, Statement and Connection objects...

    Sure. A fine example of seperating an algorithm from the container it operates on (to borrow some speak from C++'s STL). I well and truly appreciate the benefit of applying closure's (or commands, templates, ...) in such a case.

    Still, to me the article seemed to suggest that closures are generically to be preffered over iterations. Which IMO is pushing it a bit. Like suggesting a strategy is better than an if statement , sort of...

    \Ron
  14. Simpler?[ Go to top ]

    What this simple Closure interface is used for are those anonymous bits of logic you might wish to pass into a block of logic.

    Java users typically use interfaces to solve this problem, or perhaps reflection.

    A better example would be something like this (untested)

    import java.util.ArrayList;
    import java.util.Iterator;

    public interface Closure
    {
        Object execute(Object o);
    }

    public class ClosureArrayUtils
    {
        public ClosureArrayUtils()
        {
        }

        // Uses closure to create new, modified list
        public static ArrayList map(ArrayList a, Closure c)
        {
            Iterator i = iterator();
            ArrayList result = new ArrayList(a.size());
            while(i.hasNext()) {
                result.add(c.execute(i.next()));
            }
            return result;
        }

        // Save non-null objects in new list
        public static ArrayList filter(ArrayList a, Closure c)
        {
            Iterator i = iterator();
            ArrayList result = new ArrayList(a.size());
            while(i.hasNext()) {
                Object r = c.execute(i.next());
                if (r != null) {
                    result.add(r);
                }
            }
            return result;
        }

        public static test()
        {
            ArrayList sample = (ArrayList)Arrays.asList(new String[]{"This", "That", "Other"});

            ArrayList uppers = ClosureArrayUtils.map(sample,
                new Closure() {
                    public Object execute(Object o) {
                        return ((String)o).toUpperCase());
                    }
                });
            ArrayList ths = ClosureArrayUtils.filter(sample,
                new Closure() {
                    public Object execute(Object o) {
                        if (((String)o).startsWith("Th")) {
                            return o;
                        } else {
                            return null;
                        }
                     }
                });
        }
    }

    It is admittedly awkward, but that's because of the syntax of the language not really being friendly to this style of programming.

    We have to cast objects, "use" wordy util names like "ClosureArrayUtils", and "Closure".

    In Scheme, say, you'd do something like this:

    (set! uppers (map samples (lambda (s) (touppercase s))))

    (set! ths (filter samples (lambda (s) (if (startswith s "Th")
                                             s ;; Then clause
                                             nil)))) ;; else clause

    So, even though this CAN be done in Java, it seems to take so much work (at least comparable work), that it's rarely done compared to languages that better support the concept.
  15. Simpler?[ Go to top ]

    It is possible to adapt any cursor/iterator based API and to convert it to callback API, but I do not know good ways to adapt callbacks. API design is a mater of taste in most of cases and iterator is prefered by low level APIs like JDBC b/c you can adapt it without problems for your taste.
    I think languge level closures is a good way to make callback style API more readable too.
  16. Use collection interfaces[ Go to top ]

    Sorry to pick on your otherwise interesting example, but:

    > import java.util.ArrayList;

    When referring to the type, you should always use the interface:

    import java.util.List;

    --
    Cedric
  17. Opinion: Closures in Java[ Go to top ]

    A few years back while I was on a project we had a guy preaching Jython. On the web people were talking about Ruby. Maybe before all this was BeanShell. And now Groovy. On all the projects I've worked on I still haven't found a reason to use one of these scripting tools. I've taken the time to go through the Groovy site, including their presentation and examples. This looks like some "cool" stuff and it has some very neat features built in and I give a lot of credit to the guys coming up with these tools (I couldn't do it). Back in my Clipper days we had "code blocks", which were essentially closures. When I went on to VB, I remember thinking I missed "code blocks". But I guess I forgot about them when I started working with Java.

    >>Why someone would prefer Groovy to Java or C#, at least it looks weird to me.

    I ask the same question. Why couldn't I just do it in Java? I've got editor support, the compiler is installed, my environment is configured for Java. Why would I try to support an additional toolset. Learn new syntax?

    >>I think Dion tends to be a little "buzzword" happy. Yesterday it was AOP >>this, Interceptor that-- today its Closures. (b/c everybody know that all the >>k00l kids are learning Ruby, and want to be Smalltalkers like their dads...

    I don't think it's ncessarily Dion. He's just "reporting" what the k00l kids are up to. When you read about AOP, opensymphony tools, the latest scripting language, whatever, I feel like I'm missing out on something or should be using a particular tool. Then when I talk to other technologist they say AO-what? What's XWork? How many people are actually using most of these technologies?

    I think what would be helpful, in addition to reporting the latest buzzwords and technologies, is how are folks using this stuff on everyday projects (besides how Cedric, Rickard, Cameron,et al, use this stuff). How will this improve the development of a J2EE application. Enuff rambling.

    My 2 cents,
    Jim
  18. Opinion: Closures in Java[ Go to top ]

    If the developers you ask about AOP say "AO-what?", do you conclude that AOP must be worthless? You ask "How many people are actually using these techniques?" Well, if you want to be the last one into the pool, that's your right, and of course there are lots of advantages to waiting until a technology has become more mature and popular. But every mighty oak starts from an acorn. Indeed, most acorns don't end up as mighty oaks, but some do.

    Closures are not a fad. They have been around for a long time, and have been studied carefully since at least the mid 1970's. Lots of people have wondered why full-fledged closures haven't appeared in languages that have become extremely popular. In fact, this was the theme of a workshop at MIT. The real answer is a long story having to do with how technology adoption works in the real world.

    But Java, unfortunately, does not have really nice closure support. And you are right in saying that moving to another language is a really big and expensive step to take, for a lot of reasons (some of which depend on which language and which implementation we're talking about). You'd be fair in saying that the advantages of really nice closures don't justify those costs; but in my opinion you'd not be fair or accurate to say that closures are basically a worthless fad.

    As for AOP, the designers of the AspectJ system have done a great deal of work to make it easy to use AOP in a way that fits very nicely with the Java language and with Java development tools. I attended an all-day seminar on AOP a while back and was very impressed: I am convinced that this is something (a) novel and (b) valuable. The next time I build a large software system I will look very hard at AOP to see whether it is one of the appropriate tools to apply.

    You're quite right to ask how people are using a new technology on real projects. For AspectJ, one place to start is
    http://www.theserverside.com/resources/AspectJreview.jsp and another is the "Publications" page at http://eclipse.org/aspectj/ What impressed me was that I could see ways to use this to solve real problems that I have encountered in the past.
  19. WTF??[ Go to top ]

    This deserves a mention ??!!
  20. Here's something a wrote a few years ago...

    http://www.c2.com/cgi/wiki?BlocksInJava

    For what it's worth.
  21. Tell Don't Ask[ Go to top ]

    This is also worth reading...

    http://www.pragmaticprogrammer.com/ppllc/papers/1998_05.html