Sunday, September 04, 2005

Rule #67 in Design

NEVER clean up resources you did not create

I hate to pick on Java, but I found a great example of this in the Java API of all places in the javax.swing.text.html.parser.Parser class. I removed a lot of the code from the method to concentrate on the violation:

/**
* Parse an HTML stream, given a DTD.
*/
public synchronized void parse(Reader in) throws IOException {
/* LOTS OF CODE REMOVED */
try {
/* WHACKED */
parseContent();
/* WHACKED */
} finally {
in.close();
}
/* MORE CODE DELETED */
}

Basically, you pass in a Reader object that obviously you have to CREATE. And what do they for you? They free your resource that you passed in. Heaven forbid, you would like to do something else with it. Besides, why would you do that? Well, that's not the point. In design, I NEVER clean up a resource I did not allocate. If it is passed into me, I do what I need to do with it and that's all. On the other hand, if I allocate it, I take pains to make sure I deallocate it. This is what I did in my C/C++ days and it was a great rule of thumb that prevented a lot of problems.

No comments: