Re: [Vala] RAII support in VALA¿??¿?



Martin (OpenGeoMap) wrote:
hi:
have Vala suppor to RAII like c++, D, c# or ruby???

http://en.wikipedia.org/wiki/Resource_acquisition_is_initialization

In c# something like this:

string line;
*using (StreamReader sr = new StreamReader("file.txt"))*
{
   line = sr.ReadLine();
}

// **sr ** is closed already!!!!!


In ruby something like this:

File.open("logfile.txt", "w+") do |logfile|
  logfile.write("hello logfile!")
end

#logfile is closed!!!!!!

regards.

I have done some file IO with GIO, since this seems to be the preferred
way for doing this now. The API is very similar to the Java IO API, with
the same strengths but also with the same problems. The correct way to
handly my resources would look like this:

----
static int main (string[] args) {
    // a reference to a file
    File my_file = File.new_for_path ("data.txt");

    DataInputStream in_stream;

    try {
        in_stream = new DataInputStream (my_file.read (null));
        string line;
        while (null != (line = in_stream.read_line (null, null))) {
            print (line);
        }
    } catch (Error e) {   // an error occured while reading the file
        critical (e.message);
    } finally {           // make sure the stream always gets closed
        close_in (in_stream);
    }
}

/**
 * Close an InputStream without throwing an exception.
 */
static void close_in (InputStream? stream,
                      Cancellable? cancellable = null)
{
    if (null != stream) {
        try {
            stream.close (cancellable);
        } catch (Error e) {
            error (e.message);
        }
    }
}
----

That's not very beautiful, but it's the same as in Java, see:

  http://www.rgagnon.com/javadetails/java-0539.html

and

  http://www.ibm.com/developerworks/java/library/j-jtp03216.html
  ("Java theory and practice: Good housekeeping practices")

What makes it complicated is the fact that close() itself may throw an
exception, too, that has to get handled.

RAII for Vala would be really cool. There are plans for automatic
resource block management in Java 7, too:

  http://tech.puredanger.com/java7/#resourceblock

There should be an interface in GLib like IClosable or IDisposable which
could be implemented for classes not only in GIO, but also in GNIO or
any other GObject library that provides access to resources, for example
to a database. Then Vala could take advantage of this interface.


Regards,

Frederik



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]