Did the developers of Java conciously abandon RAII?

Posted by JoelFan on Programmers See other posts from Programmers or by JoelFan
Published on 2011-11-07T14:45:26Z Indexed on 2012/03/20 17:38 UTC
Read the original article Hit count: 367

Filed under:
|
|
|

As a long-time C# programmer, I have recently come to learn more about the advantages of Resource Acquisition Is Initialization (RAII). In particular, I have discovered that the C# idiom:

using (my dbConn = new DbConnection(connStr) {
    // do stuff with dbConn
}

has the C++ equivalent:

{
    DbConnection dbConn(connStr);
    // do stuff with dbConn
}

meaning that remembering to enclose the use of resources like DbConnection in a using block is unnecessary in C++ ! This seems to a major advantage of C++. This is even more convincing when you consider a class that has an instance member of type DbConnection, for example

class Foo {
    DbConnection dbConn;

    // ...
}

In C# I would need to have Foo implement IDisposable as such:

class Foo : IDisposable {
    DbConnection dbConn;

    public void Dispose()
    {       
        dbConn.Dispose();
    }
}

and what's worse, every user of Foo would need to remember to enclose Foo in a using block, like:

   using (var foo = new Foo()) {
       // do stuff with "foo"
   }

Now looking at C# and its Java roots I am wondering... did the developers of Java fully appreciate what they were giving up when they abandoned the stack in favor of the heap, thus abandoning RAII?

(Similarly, did Stroustrup fully appreciate the significance of RAII?)

© Programmers or respective owner

Related posts about java

Related posts about c#