Transferring scripting idioms to Java - Part 3 - General Philosophy Continued



Part 1 - Introduction

Part 2 - General Philosophy



I ended my previous discussion of functors, you might say, perfunctorily. Before diving on the next part of this essay let me add the following example of the fore mentioned functor in action.
The idea of the following example is to mimic a scripting idiom for processing text files.


LineProcessor lp = new LineProcessor(new File("foo.foo"));
lp.lookEachLine(new IStringFunctor() {
public Object call(String s) {
System.out.println(s);
}
});


In this example we create a LineProcessor class for reading a file called foo.foo. We then call its’ lookEachLine method passing in a simple functor that prints out each line.
.


Compare this to some Ruby code that does the same thing:


aFile = File.new(“foo.foo”)
aFile.each_line( ) do |line|
puts line.dump
end

Now compare this to some standard Java code.

BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("foo.foo"));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}

} catch (IOException e) {
// do something with the exception?
}
finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
// do something with the exception?
}
}
}

Both the Ruby and the Java with the scripting library are a lot more concise than the straight Java. It’s this sort of reduction in template code this library is aiming to achieve.


Comments

Unknown said…
You can also get return values if you want by enhancing this technique:

Closures with return values in Java

Popular posts from this blog

Running roughshod or ripshod

Axis, Axes, Axii?

Gay Cowboys