[ Content | View menu ]

Understanding Why

Mark Mzyk | September 6, 2008

The title of this post is taken verbatim from a post of the same name by Jay Fields.

Jay’s point is that it isn’t enough to go through the motions of being a developer. Part of being a developer is understanding the point of the motions you’re going through.  If you don’t understand why, you can’t understand the good or the harm you’re causing.

Recently on a project, I checked in some Python code that used several try except finally blocks, looking similar to this stub code:

try:
    session.open()
    do stuff
except:
     handleException()
finally:
    session.close()

The code acquired a database connection and I used the finally block to ensure the connection was closed, preventing any leaks.

When working on the code I had inserted some tabs instead of spaces. When another developer opened the same code in his editor, it complained about the tabs vs. spaces, but didn’t offer an explanation for the error it was reporting, only reporting an error. The developer failed to ask why the error was being reported and also failed to ask why I had written the code as I had.

The result was that the code was rewritten as this:

try:
    session.open()
    do stuff
    session.close()
except:
    session.close()
    handleException()

There is now duplicate code in the form of the session.close() call and the finally block has been removed. The code is less explicit and more repetitive (although it happens to end up being the same number of lines).

Muddling of code and an unneeded rewrite occurred all because of a failure to ask why. Listen to Jay. Ask yourself why before you code and before you start changing code others have written. It will lead to better code.