Monday, February 01, 2010

Java Needs Destructors

I've been a Java programmer for seven years now. Java is no C++, but it's not a bad language, especially in it's Java 6 incarnation. There are just a few things about it, though, that continue to really get under my skin. This biggest is the lack of destructors in Java. In C++, you'll often see code like this:
public void foo() {
ResourceIntensiveClass ric = new ResourceIntensiveClass("have bugs");
ric.initiateResourceLockingStuff();
ric.exceptionRiddledFunction();
}
And you can be comfortable that, if written correctly, ResourceIntesiveClass' destructor will be called and all resources freed when ric goes out of scope, regardless of whether it was under control or because of an exception thrown by ResourceIntensiveClass::exceptionRiddledFunction().

Unfortunately, when Java was being designed, the designers seem to want to get rid of every aspect of C++ that gave people trouble. Many people have trouble with destructors, so they are completely non-existent in Java. The only possible replacement, the finally clause to the try/catch block, requires the programmers who use a class to remember to call resource freeing methods of a class in their finally blocks. Every time. Without fail. Good luck. Java code is needlessly much more verbose for the same task than many other languages. Consider this Java equivalent to the code above:
public void foo() throws Exception {
ResourceIntensiveClass ric = null;
try {
ric = new ResourceIntensiveClass("have bugs");
ric.initiateResourceLockingStuff();
ric.exceptionRiddledFunction();
} finally {
if (ric != null) {
ric.manuallyCalledCleanupMethod();
}
}
}
Twelve lines to the first example's five lines. More typing and more opportunities for programmer induced bugs.

When is Java going to grow up and get destructors?

No comments:

Post a Comment