Subscribe to the Free Print Edition!
Celebrating 25 Years

Java seeks closure on closures

By Joab Jackson

SAN FRANCISCO—If there is one topic that seems to get Java programmers excited, it is the question of whether to include a new feature called closures in the next version of Java. Advocates say closures would bring more flexibility to the language, but others worry it might encourage bad coding practices and make the language more difficult to work with.

The debate surfaced again today at the JavaOne conference here, when Neal Gafter, a software engineer at Google, presented his proposed specification for adding closures to Java. The specification, called BGGA, was named after its authors: Gilad Bracha, Gafter, James Gosling and Peter von der Ahé. Gosling is the founder of Java.

Closures are blocks of code with unbound variables, or variables that are not assigned until the closure is called. Although they occur in Haskell and some other functional programming languages that are used relatively rarely, closures are not a feature of Java.

"A closure expression in a program…creates an object. The object wraps up the code that is the body of the closure and anything that is referenced from enclosing scope, such as local variable. It wraps them up and packages them in an implementation of some interface, and that interface is whatever interface type is expected in the context of the program," Gafter said. Closures are sometimes called function objects or anonymous functions.

Closures look different from most Java code. BGGA introduces a new syntactic form for Java, one markedly different from the usual Java format, resembling the often-dense format of functional languages.

Nonetheless, adding BGGA-styled closure functionality to Java 7 would be beneficial in a number of ways, Gafter said. It could potentially reduce the amount boilerplate code a programmer must write. Programmers could write a single closure that could be called from multiple instances by using a short application programming interface. He offered one example of a performance monitoring function, which may be added in selected places in a program. The function collects performance data from in various points in the program and then submits the results to a database. Without closures, the programmer must write much the same code repeatedly. Under closures however, the code could be defined as an application programming interface that could easily be called within the main body of the program.



GCN Popup