Austin Clements

A Short Guide to Writing Readable Code

A lot of people ask me how much they should comment their project code. There's no magic rule, but here are some pointers.

Commenting

"Instead of imagining that our main task is to instruct a computer what to do, let us concentrate rather on explaining to human beings what we want a computer to do." -- Knuth

Commenting isn't only about communicating with other people. Two weeks after you've written your code, you won't remember how it works or what it does, so you should still be able to read it. "But I'm never going to read my projects after I hand them in!" Maybe not, but I will, and this is an excellent guideline for making your programs understandable by others, too. It's also an excellent habit to get into on the off chance that you ever have to write any code for a real project.

Document the top-level structure of your code. Nobody who uses your code (which includes you) wants to dig into the body of a procedure just to determine what it does. Thus, procedures should be documented so that it's clear what they do and how to use them. That way, you can quickly find the procedure that you need, or get a good idea of how a program works just by skimming over it. (I like to put such comments just above each procedure. Think of them as mini-abstracts for each procedure.)

Document the internals of your code. The world isn't perfect. Procedures aren't write-once. You will inevitably have to go back and change the code inside your procedures, so there should also be enough documentation inside the body of a procedure to make it clear how it works.

Beyond Commenting

Comments aren't the only form of documentation. Function names, argument names, and variable names are also key parts of documentation. Even the way that you structure your code is a form of documentation. For example, if you want to introduce local variables, use let instead of manually desugaring it into a lambda to document that your intent is to introduce local variables, not to create procedures. The computer certainly doesn't care which one you use. Forms like let exist so you can naturally capture your intent.

Links

"Comment my code? Why do you think they call it 'code'?" -- T-shirt