Sunday, April 13, 2008

Lonely Variables

First, hello to consumers of my new blog. All those "lonely variables" out there who, like me, are looking out for fellow software engineers who actually care about what they do.

Second, to the subject of this post. Why, oh why, do programmers - esp. VM programmers (Java / C#) - feel the need to make variables lonely. Don't they know about locality of scope? Haven't they heard about try-finally?

For that matter, why is try-finally something so rarely used/understood? For sure it's a poor bring-your-own-cognisance relation of deterministic destruction (provided by the old curmudgeon of languages, C++), but at least it works.

Consider the following code:

  File file = null;

  try {
    file = new File("myFile");
    file.write( // blah blah
    file.close();
  }
  catch(IOException e) {
    // deal with exception

    // close file
    if(file != null) {
      file.close();
    }
  }

why not use a try-finally, and reduce the effort, and the risk of maintenance mistakes?

  try {
    File file = new File("myFile");
    try {
      file.write( // blah blah
    }
    finally {
      file.close();
    }
  }
  catch(IOException e) {
    // deal with exception
  }

Now which one is simpler? Which?