Application
    development
         is the
    union
         of
 creativity & logic.

Write Code Comments First

[Drupal and Web Development]

I was reading an article today about common mistakes in writing JavaScript when I got to the section on comments and it reminded me of a technique I developed early in my career and that I teach to junior developers.

I write my function's comments first, before I write any code.

When I was a young developer, I was gung-ho about diving into programming head first, typically with little forethought about the low-level architecture that I needed to apply. Since I am self-taught, I had nobody to teach me the errors of this except for that finest of mentors: experience. Over the years, I have learned to think ahead and understand how all of the pieces will need to fit together; learned when it makes sense to break code out into a separate function and to have a (generally) good sense of when I'm over-engineering a solution.

To that end, one technique that came naturally to me is the idea of writing out the primary objectives in a function first. Perhaps this seems obvious to some, but far too many developers consider comments to be an after-thought. I find that, by jotting down the major points first, it ensures that I think the function through from start to finish and have those "ah ha!" moments before I've started to code.

Here is a simple example from a recent project of mine, a custom Drupal module:


function mymodule_processCustomerUpdates($customer) {
// confirm required object values
// retrieve related nodes
// iterate over nodes and check for updates
// validate changes
// update and save customer node
// create success message
// handle exceptions
}

Although this seems rudimentary, I find it to be invaluable when I need to program functions of even moderate complexity. In fact, for all but the most basic functions I follow this technique even if there just a couple of lines.

Of course, this first step serves only as an outline and I always flesh out the comments with additional detail as I go along. And if I have a series of related functions, I often outline all of them before I begin coding any individual piece. The more complex the solution, the greater the need to think it through first and save yourself much trouble later.