indiWiz.com

Subhash's Tech Log

Beautiful Closures

without comments

One of the irritating things when writing code in Java is when managing files or database resources. We have to write so much redundant code:

File f = new File("/etc/passwd");
BufferedReader br = null;
try{
  br = new BufferedReader(new FileReader(f));
  String str;
  while((str=br.readLine())!=null){
    System.out.println(str);
  }
}
catch(IOException ex){
  ...
}
finally{
  if(br != null){
    try{
      br.close();
    }
    catch(IOException ex){
      ...
    }
  }
}

So much redundancy is ground for human errors. Issues like these are beautifully solved using programming concept called Closures. For example, in the newly released 2.6 version of Python, the same would be written as:

with open('/etc/passwd', 'r') as f:
    for line in f:
        print line

In the above code, even when an exception is raised during file read, the file is gracefully closed when the control exits with block. A similar example in Groovy:

File f = new File("/etc/passwd")
f.eachLine{
  line ->
  println line
}

Martin Fowler has written a short introduction to Closures.

Written by Subhash Chandran

November 18th, 2008 at 8:27 am

Posted in Java, Scripting

Tagged with , , , ,

Leave a Reply