Wednesday, March 10, 2004

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(""));
lp.lookEachLine(new IStringFunctor() {
public Object call(String s) {

In this example we create a LineProcessor class for reading a file called 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 =“”)
aFile.each_line( ) do |line|
puts line.dump

Now compare this to some standard Java code.

BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(""));
String line;
while ((line = br.readLine()) != null) {

} catch (IOException e) {
// do something with the exception?
finally {
if (br != null) {
try {
} 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.

Post a Comment
The Out Campaign: Scarlet Letter of Atheism