[ 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.

One Comment

  1. Comment by Kevin:

    Excellent point Mark.

    I once worked with a developer that had written some code to move a recordset pointer to the end of the set and then back to the begining again before working on it. When I asked him why he’d done something that seemed incredibly redundnant he told me “it’s just what we do to get it to work”. I found out that he’d copy/pasted these two lines of code all over the codebase and not once stopped to ask what it was really doing or why it should be doing it*.

    My mentor at the time refered to it as “voodoo programming”, because it’s like waving a dead chicken in the air before you hit execute – you don’t know why it works but this one time it did so you just kept doing it.

    kevin

    * it turned out that the code in question was originally written to get around a bug with a (long since replaced) database driver and multi-directional recordsets. Since we were using a different driver (hell, an entirely different DBMS) and really just needed a forward-only recordset, this code really was a complete waste of resources – not just in one place but in many.

    September 6, 2008 @ 18:25