package com.test;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import com.google.common.base.Join;
public class BGGAFilter<T> {
public static void main(String[] args) {
List<Integer> ints = new ArrayList<Integer>();
for( int i = 1; i <= 10; i++)
ints.add(new Integer(i));
BGGAFilter<Integer> filter = new BGGAFilter<Integer>();
List<Integer> filtered = filter.filter(ints, { Integer x => x % 2 == 0 });
System.out.println("(" + Join.join(", ", filtered) + ")" );
}
public List<T> filter(List<T> in, { T => boolean } predicate) {
List<T> out = new ArrayList<T>();
for( T item : in)
if( predicate.invoke(item))
out.add(item);
return out;
}
}
This is not a completely apples-to-apples comparison with my previous Java example using the Google Collections API. You'll notice that in the above example, I had to implement the filter method, whereas the google collections API provides it for us. Now that I've seen examples in Scala, Java, and Java + BGGA, I couple of questions come to mind:
- Is the BGGA example 'better' than the straight Java example? If you think of the language itself as an API, and programmers as users of your API, then you start thinking in terms of usability, simplicity, power and self-documenting code. That is, many (but not all) of Josh Bloch's bumper sticker API design principles apply. The BGGA example carries much less syntactic weight than the straight Java example. The former focuses directly on what the code is doing, whereas the latter devotes many more characters to how the code does the job. Following Josh Bloch's advice to "keep APIs free of implementation details," I would choose BGGA over straight Java. This is by no means a comprehensive comparison, but rather a shard of evidence in the Java closures debate. The other thing to consider, of course, is that I am not even comparing FCM and CICE, two other leading Java closures proposals. Based on a very cursory evaluation, I have chosen to hone in on BGGA.
- If the use of closures and anonymous functions is instrumental in my problem space, why not just use a language that supports functional programming, such as Scala? If you need true functional programming now, then the answer is simple. Use a functional language. On the hypothetical side, suppose BGGA makes it into Java, and you just need closures. This one is more difficult for me to answer. You need to assess: What is the talent on my team? How much time do I have to complete the project (do we have time to learn)? Try and come up with one or more use cases that would demonstrate why one would be better than the other. For me, the jury's still out. I'm heartened by the fact that Scala is built on the JVM, and has tight integration with existing Java libraries. I believe this will certainly help its adoption.