How to: Document your code

I have one rule to documenting code:

  1. Why, not what: Explain why the code is doing what it's doing, not what it is doing.

Clearly this doesn't apply to code that is an API of some kind, where the code is the interface. Everywhere else, though, where the code is a mechanism to get the front-facing work done, explain the decisions that went into making the code do what it is.

Some hypothetical examples:

# Use port 3000 instead of 80 because that's what 
# Corporate is allowing us to use through the firewall.

# Force this column to be a bigger font for Stan in Accounting.

# Use Imager instead of Image::Magick because of
# incompatibilities with frongdoodle mode in PNG images.

# Can't use a JOIN here because MySQL 5.0's optmizer
# makes a bad plan.  This is supposed to get fixed in 5.1.  See 
# http://wiki.mycompany/MySQL_optimization_problems for the details

Note how all these examples explain something that may be out of the ordinary, or make the next reader (maybe even you) think "What the hell was this guy thinking?" A well-placed, well-written, well-thought-out comment will make the reader say "Aaaah, THAT'S why it's like that!"


1 TrackBacks

Listed below are links to blogs that reference this entry: How to: Document your code.

TrackBack URL for this entry:

» Story added from

Your story has been submitted to! Come and promote your article by voting for it here on FSDaily! Read More


Max said:

Yes. Yes, yes. Thank you. :-)

This is absolutely true. :-)


havel said:

You should also document what it is doing if convoluted. I'm currently going through complex code someone else wrote, and I'm having to break the more complex statements into parts and then document it.

Leave a comment

About this Entry

This page contains a single entry by Andy Lester published on December 3, 2007 10:27 PM.

Who's making bogus web requests? was the previous entry in this blog.

How to: Tell your users they are not worth your time is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.

Other Perl Sites

Other Swell Blogs

  • geek2geek: An ongoing analysis of how geeks communicate, how we fail and how to fix it.