Wednesday, May 9, 2012

Comments considered harmful 2

I am getting "Too many open files" errors. So I check every usage of files and streams, and make sure I always close them. Here is a snippet I found that was not closing the out stream after use (empty lines and failure detection suppressed):

JspWriter out = pageContext.getOut();
if (errorMessageToUser == null)
{
    drawCalendar(out);
} else {
    out.println(errorMessageToUser);
}


So I add a line closing the writer, like this:

JspWriter out = pageContext.getOut();
try {
    if (errorMessageToUser == null)
    {
        drawCalendar(out);
    } else {
        out.println(errorMessageToUser);
    }
} finally {
    out.close();
}


Of course, this broke one of the golden rules, saying that you only should close files that you have opened yourself. This writer was opened by the jsp framework, so I got a "Stream already closed" error somewhere else when jsp wanted to close it.

I need some way to avoid redoing the same mistake. My first attempt was to add a comment:

JspWriter out = pageContext.getOut(); // Don't close
if (errorMessageToUser == null)
{
    drawCalendar(out);
} else {
    out.println(errorMessageToUser);
}


Now, I have a problem with this kind of comments. It is localized with the declaration, so to see it, you have to go back there. My recommended practice today is to try to incorporate the comment into the variable name. So this is my present version of this code:

JspWriter outDontClose = pageContext.getOut();
if (errorMessageToUser == null)
{
    drawCalendar(outDontClose);
} else {
      outDontClose.println(errorMessageToUser);
}


I find this pattern outstanding. By being its own comment, the code tells me about its semantics, its rules of usage. And, best of all, it is not localized to the point of declaration. I am reminded of the rules every time I see the variable name.