Home

Advertisement

Java.has("closures"); //yet, too verbose

  • May. 21st, 2009 at 9:50 PM

The code bellow shows how Java annonynous inner classes are just static typed closures, with all verbosity but also all behaviour needed :-)

1:import java.util.LinkedList;
2:
3:public class VerboseClosures {
4:    public static void main(String[] args) {
5:        MyList langs = new MyList();
6:        langs.add("Java");
7:        langs.add("Scala");
8:        langs.add("Ruby");
9:
10:        final String msg = "Got ya";
11:        langs.each(new HandleAll() {
12:            public void handle(String s) {
13:                System.out.println(msg + ": [" + s + "]");
14:            }
15:        });
16:    }
17:}
18:
19:class MyList extends LinkedList<String> {
20:    void each(HandleAll handler) {
21:        for (String s : this) {
22:            handler.handle(s);
23:        }
24:    }
25:}
26:
27:interface HandleAll { void handle(String s); }

Back on 2004, Fowler said about closures:

So the first crucial point about closures is that they are a block of code plus the bindings to the environment they came from. This is the formal thing that sets closures apart from function pointers and similar techniques.(Java's anonymous inner classes can access locals - but only if they are final.)

As we can see on lines 10 and 13 our method being sent to the each operation is capable of accessing a local variable (marked as final though). Of course, closures should be much more easy to manually write, that's half of their strengh.

This is again, just to exemplify the concept, even so, anonymous inner classes are extremely handy in the absence of "normal" closures backed up by good syntax sugar.

(*) Extending LinkedList is not encourage, but this is just to make the example simpler

(**) In favour of Java I can say that free IDEs like Eclipse can generate all this verbose code with a few keystrokes (and programmers are more than used to that with their editors, hehe). Hence, leaving us the the best of both worlds, closures but still all the good side of static typing, like safe automated refactorings. And the chances you to be using already a IDE for Java development are rocket high...

(***) Closures are much more pleasant with proper syntax sugar, there's no way do deni it.



Comment Form

From:
(will be screened)
Help(will be screened)
Identity URL: 
(will be screened)
Username:
Password:
Don't have an account? Create one now.
Subject:
No HTML allowed in subject
   Help
Message:

 
Notice! This user has turned on the option that logs your IP address when posting. Help

Latest Month

November 2009
S M T W T F S
1234567
891011121314
15161718192021
22232425262728
2930     

Tags

Powered by LiveJournal.com
Designed by Tiffany Chow