feed

CollectionsUtils makes me think I need closures in Java

Working with CollectionUtils’s Predicate makes me think: I need closures in Java. Consider the following code snippets of equvalent Java and Ruby code.

Java:

public List test(List data) {
LinkedList result = new LinkedList;
for(Iterator i = data.iterator(); i.hasNext();) {
Address address = (Address) i.next();
if("Germany".equals(address.getCountry())) {
result.add(address);
}
}
return result;
}

And ruby:

def test(data)
return data.collect { |address|
"Germany".equals(address.getAddress)
}
}

The real power of closures comes with resource management:

File.open("foo.txt") { |file|
// do sth with file which even might throw an exception
}
//Filehandle is closed here (automatically)

In Ruby this is implemented like this:

class Resoucre
def Resource.open(arg1)
f = createThisResource(arg1); // Create Resource
yield f // Call the block passed in with argument f
f.close() // Cleanup
end
end

Resource.open("foo") { |aResource|
// do sth useful with the resource
...
}
// here at the block end, the processing continues in Resource.open (after the yield call)

How could this work in java?

First, how can we express this in java?

Today’s Java, this is like CollectionUtils work

Usage:

Collection result = myCollection.findAll(new BooleanFilter() {
public void isMatch(Object candidate) {
return ((Address) candidate).getCountry().equals("Germany");
}
});

Definition of Iterator:

class MyCollection extends Collection {
public Collection findAll(BooleanFilter filter) {
LinkedList result = new LinkedList();
for(Iterator i = iterator(); i.hasNext(); ) {
Object current = i.next();
if(filter(i.next()) {
result.add(current);
}
}
return result;
}
}

This is rather verbose, usage needs class casting and a new Interface has to be introduced.

A suggestion to adopt a ruby like syntax

First, the usage:

String country = "Germany";
Collection result = myCollection.findAll(closure {
country.equals(candidate.getCountry());
});

And the implementation of MyCollection.findAll:


class MyCollection extends Collection {
public Collection findAll(boolean closure filter(Object) {
LinkedList result = new LinkedList();
this.iterate(void closure(Object current)) {
if(filter(current)) {
result.add(current);
}
}
return result;
}
}

The difference to today is a new closure keyword and some syntactic sugar. I think the "new" syntax could easily pre-compiled to valid java code (although I don't like precompilers that r on propriatary syntax extensions). This is a draft of my thoughts, the benefit isn't that big if you compare the two versions. Strange. I think the ruby version feels so much cleaner because of it's lack of type declaration.

{ Comments are closed! }

terms
research
guidelines
Bear