October 28, 2005 - Finalizers and with-open-file or File.open

Tom Ball has an interesting blog entry on a good use for finalizers. Library designers can use it to let users of their library know when they have not cleaned up a resource.

The comments on the entry are enlightening. One comments that this could slow down garbage collection. Another comments that they always make sure that any code in their library that has system resource handles manages the closing of that code. I have used this approach in the past, but it was somewhat ugly.

Recently, I have been coding in Ruby and it has a very nice idiom for this similar to an old lisp idiom, with-open-file.

In Ruby, one way to use a file resource is to call a class method with the filename, and then provide it a block that operates on the file. This call automatically takes care of closing the File resource after you are done. It looks like this:

File.open("/tmp/myfile", "r") { |file| puts file.read }

Posted by Bob Evans at October 28, 2005 11:17 AM

Trackback Pings

TrackBack URL for this entry:


Post a comment

Remember Me?