Jim Freeze <jim / freeze.org> wrote:
>
>I have a class where the initializer takes a filename
>and opens a file. The class has several methods to let
>the user get information from the file.
>
>The problem is, I don't know how to have the class
>close the file automatically like a destructor would
>in C++. (Maybe I have missed something big here)

When using true garbage collection the destruction
happens when garbage collection is run, and not at a
predictable point in program flow.  This makes reliable
destructors hard.

>I see 2 options:
>
>1) Put the burden on the user with #begin #end
>
>begin
>   c = Myclass.new("file")
>   c.meth1
>   c.meth2
>
>   ensure
>     c.close
>end
>
Possible.
>
>2) Or I could store the file pointer in the class and
>have each method open the file, move to the proper location,
>do its thing, save the file pointer, close the file.
>But this seems kind of kludgy.
>
Possible.
>
>Any other ideas out there?
>
For many problems a clean solution is to provide an API
that is iterator based.  Then you can call the method,
it calls your block until you hit a finishing condition,
and then the method closes the file.  Ruby does this in
some methods, for instance File.open.

This third solution works well with the first.  If you
have a simple problem, you have a simple clean API to
use.  If your control flow is more complex, you can
still get reliable cleanup.  If cleanup is not a concern
(your program will exit soon anyways) then you don't
take a performance hit for it.

Cheers,
Ben
_________________________________________________________________
Get your FREE download of MSN Explorer at http://explorer.msn.com