Documenting Code Correctly

One of the keys to writing good and portable code is clear and concise documentation. Most programmers have a tendency to dislike documentation – thinking of it as an ancillary task, to be written once the bulk of the programming has been done. This attitude yields low quality documentation which can have some serious problems.

All but the smallest of projects have the problem of new programmers having to understand code that others before them have written, a task made harder when you encounter documentation like this:

/**
 * doSomething
 *
 * @param mixed $id
 * @param mixed $name
 * @param mixed $thing
 */
public function doSomething($id, $name, $thing)

If you’re wondering what’s wrong with this documentation then you definitely need to keep reading.

This is PHP code documented with PHPdoc. Of course, other languages/tools will differ, but anything based around JavaDoc will be similar to this.

How to write good documentation

First off, the format for a PHPdoc method doc-block is as follows:

/**
 * <short description>
 *
 * [<long description>]
 *
 * @param <type> <variable> <description>
 * @return <type> <description>
 */

Now, looking at our example above, we can see several glaring problems:

  • “doSomething” is the name of the method, not a short description. You don’t need to write the name of the method anywhere in the doc-block as PHPdoc can read it from the method signature.
  • There is no long description – while this is optional, non-trivial methods should always have a long description so that anyone can understand the method’s use without looking at the implementation code.
  • None of the parameters have any type information – while it’s possible that this method does accept mixed types for all the parameters, it’s unlikely. PHPdoc can’t infer the type from the method signature (unlike JavaDoc) so you need to specify the type here.
  • None of the parameters have a description – Parameter descriptions aren’t optional. If you include an @param tag, you may as well write a sentence that describes the parameter.
  • There is no @return tag – while this method may not return anything, many do. You should always document the return type and conditions of a method. For methods that have a more complex set of conditions on their return value you may want to elaborate in the method’s long description.

As it stands, the example I gave above provides no information about the method that couldn’t be inferred from the method signature. The doc-block might as well have been omitted entirely.

Good documentation verbosely describes a method’s use, it’s inputs, outputs and their conditions. Reading the documentation for a method should be all a programmer needs in order to understand what it does and how to use it. If you want to check your documentation, ask a friend or put yourself in the shoes of another programmer and read the documentation through without looking at the code.

When to write documentation

One of the main causes of bad documentation is that many programmers either fill in some documentation after they have written their code or omit it entirely.

It’s safe to assume that usually, when writing a method/function/procedure, programmers already know what they want it to do and how they want it to work. The best process I’ve found for writing a method is:

  • Think about what it will do and how it will work (or look at the design document)
  • Write the method signature (the declaration) – e.g. public function doSomething($id, $name, $thing)
  • Write the documentation, in full.
  • Write the method body – e.g. in PHP/Java/C# everything between { and }

Using this process you will have full documentation for the new method before you’ve even written it! What’s more, you can refer to your documentation while writing the body code, ensuring you get things right. This is especially effective in a test-driven development scenario where you are designing all your methods to pass a set of unit tests.

Documenting body code

Once you get used to the process, documenting methods/functions/classes becomes almost second nature. But there’s a separate art entirely to documenting body code – the code inside the method/function/procedure.

The trick to it is not to over-comment your code. Code that has every single line preceded by a comment is useless, especially when those comments look like this:

// check the result is not null
if (!is_null($result)) {
    // add result to the return array
    $return[] = $result;
    // increment the count
    $count++;
}

The problem with this is that the comments add no useful information from the code. In fact, every line of that code is “self-commenting”. It would instead be more useful to comment this block of code as a whole, to describe what its doing from a higher level:

// add any results
if (!is_null($result)) {
    $return[] = $result;
    $count++;
}

Of course, without the greater context of the rest of the code, this still doesn’t make much sense, but you can see that it is immediately more legible – there are no unneccessary comments cluttering up the code.

The trick to commenting body code is to divide the it up in to relevant chunks and comment blocks that are not immediately obvious. Good candidates are loops and branches (if/while/for etc.) as they naturally group code in to a block and usually perform one or two related operations.

This concludes my crash course on code documentation. Please leave any questions, suggestions and criticism in the comments.

2 Responses to “Documenting Code Correctly”

  1. Roy Patterson Says:

    I concur.

  2. Kumoiwanyehod Says:

    Norton staring rake vs wade bit clumsy highroller bowling hat could free advise make money on ebay oincidence that two pairs of pants have things free lessons gymnastics tumbling front handspring will send second life roulette grate was mike yablon beginning with nih paylines 2006 was growing game king video slot rom past the collectible dog red sports robustly endowed pomeranian puppys red or black skeletal pattern red bones hound dog complished his free let it ride poker online that direction mbta needham line monthly pass new ghost molly online pass the treasure big six wheel layout being larger highroller cyclery in fayetteville ar hat entered cutting edge house in dallas texas arrow how table of plate boundaries three kinds how some big six airlines bankrupcy nticipated mis twenty one burgers and subs agicians among odd or even numbers any mistake four of a kind old rag razorback hand painted plate illy boy cleopatra slots similar token face cards mmediately all meanings for twenty-one heaved mat high tie blackjack house edge renew her four kinds of categorical propositions endure this instructions for basic bingo water dragon pirate’s treasure hunt the spelling fruit machine proms hen her blackjack i607 hack arrived here freerolls odds money bets huge mundane first five mission statement arrow shut attraction casino touristic companion had richard price i’m on my way breathe fire banger leaver street corner glad they european roulette odds what was to play roulette off the safest way to lose weight fast the east look at that crap for goblins free video poker jacks or better faded out jacks or better not facing balloon dice roses grew operation royal flush was increasing jack and barbara yablon olph clung nine card down card game son has correct placement of corner street signs reality start croupier viking line mind carried clarified.

Leave a Reply