Java.net Poll on Closures
Java.net is having a poll on which version of closures is preferred for Java 7. I think this is a great opportunity for First-Class Methods (FCM) to get some attention as a worthy contender.Closures offer us the opportunity to make our Java code simpler by making the Java language more complex. The tradeoff is - how much simpler will our programs get, and how much more complex will the language get? I feel that First-Class Methods presents the best balance between language complexity and code simplicity.
First Class Classes
Do you ever use Class objects in your application? For example, to instantiate a logger:
public class RealDeliveryService {
private static final Logger logger = Loggers.forClass(RealDeliveryService.class);
...
}
... or to bind a type with Guice:
public void configure() {
bind(DeliveryService.class).to(RealDeliveryService.class);
bind(User.class).toProvider(UserProvider.class);
...
}
Class literals are powerful, typesafe, and easy to use. FCM takes the power of Class literals and extends it to methods and fields.
First Class Methods
With this, much boilerplate code vanishes. Consider sorting Deliveries by price:
List<Delivery> deliveries = ...
Comparator<Delivery> orderByPrice = new Comparator<Delivery>() {
public int compare(Delivery a, Delivery b) {
return a.getPrice().compareTo(b.getPrice());
}
}
Collections.sort(orderByPrice, deliveries);
With FCM, we just create a comparator from the
getPrice
method: List<Delivery> deliveries = ...
Comparator<Delivery> orderByPrice = MethodComparator.newInstance(Delivery#getPrice());
Collections.sort(orderByPrice, deliveries);
FCM can dramatically reduce boilerplate throughout your application:
- If you're writing a Swing app, you'll be able to specify a no-argument method to
invokeLater
, rather than defining an anonymousRunnable
. - If you're writing a web app, FCM will lend additional typesafety to your libraries like Struts 2.
- And FCM invites a new generation of frameworks and tools to be created. Terse like ruby, typesafe like Java.
Help FCM Gain Mindshare
Please, familiarize yourself with the proposals and vote for a better Java.