Writing Readable Code
code you' write function comments time writing paper don'
Just about everyone could use some pointers on how to write better code. Let's take a look at seven time-proven ways to write your code so that you can actually go back to it later and be able to understand it, or hand it to another developer who can use it and modify it easily.
1. Design your code before you code it.
I can't repeat this enough; never write code on the fly. You should always have sketched out some pseudocode explaining what the code will do (at a higher level) before you start coding. The only exception to this rule is code that you've already written innumerable times (e.g. finding one element in an array).
I say this because I always heard this advice and, predictably enough, never followed it until I started working on large projects using code I simply couldn't visualize in my head. When I started roughing out the code on paper, I found that I would come up with different approaches to problems and work out difficulties much more quickly.
Sketching out code before writing it will solidify in your mind exactly what you want to do, and will save you a lot of time sitting in front of a computer screen, trying different approaches to an algorithm. I don't know why, but you will save time.
I think it has to do with mindset; when you're typing code, you're in "programmer mode," trying to get each individual little line right. When you've writing out pseudocode on a legal pad, you're in "design mode," and you're able to look at things from a fresh, higher-level perspective.
2. Comment your code as you write it, not after.
Comments. Comments. Comments. I can't count the number of times I've berated a piece of code for not having enough comments, but I can't remember ever being annoyed at code that had too many comments. The moral is simple: write as many comments as possible. Don't comment something that's obvious (e.g. "i = 0; /* Assign the value 0 to the integer variable i */"), but try to explain yourself as you code (e.g. perc = int(cnt / num_els * 100) /* perc = percent complete, from 0 to 100 */).
I recommend writing comments as you're writing the code itself, mainly because we're much less likely to go back in and add useful, meaningful comments later. Do it as you're coding, and the comments have a much better chance of being both meaningful and complete.
3. Each function should have a meaningful explanatory header comment.
Describe exactly what the function is supposed to do, what it assumes about incoming data, and any gotchas in the results. This way, rather than having to read a fifty-line function to figure out what it does, all you'd have to do is read a one- or two-sentence description.
The pseodocode you sketched out when designing this function can also come in very handy in writing the explanation. Some programmers include the psueodocode with the description.
4. Use indents and margins appropriately.
This quickly becomes a habit, but a surprising number of programmers don't indent properly. Each new loop, if statement, or function should have its code indented one level further (just hit the space bar a few times, or hit [TAB]). Make sure that you return to the previous level of indentation when you're done with each block, too.
Blank lines are also surprisingly useful in increasing the readability of your code. Three or four blank lines between each function will visibly separate those functions from each other, and your brain will take that much less time in identifying where one ends and another begins.
5. Keep functions direct and to-the-point.
I've lost count of the number of times I've seen one function that's got all sorts of processing dumped into it (I've written a number of them myself). Separate out distinct algorithms into their own functions. Redesign the big function into several smaller functions that are easier for people to read and understand.
An example: Don't write one function, moveMonsters() to do all the processing of moving monsters. Break it out so that it calls isMonsterNearWall(), getPlayerPosition(), move1Monster(), etc.
6. Always use descriptive variable names.
Code becomes orders of magnitude more difficult to debug when important variables are named i, t, temp, var, var1, and so forth. If you have a variable to store the player's health, don't name it h; name it playerHealth.
7. If you're confused about an algorithm, run it on paper
This applies both to code that you've written and no longer understand, and to code that you've gotten from an outside source. Here's how it works:
Print out your code, then take a blank sheet of paper and list on the paper all of the variables used in the code. Then go through the code line by line, writing down the values of variables as they're changed by the algorithm. Pretend you're the computer. Use a calculator for advanced mathematical functions. Write down any output on a separate piece of paper.
After a few iterations of this, the basic structure and intent of an algorithm should become very clear. This is invaluable for debugging, too, since code often doesn't work the way you think it will work.
Remember that most of the time you spend on programming is spent modifying existing code; very little time (comparatively) is actually spent adding in new stuff. This means that you'll be spending a lot of time reading through your code, and so it makes sense to invest the time and effort in teaching yourself how to write code that's readable. Readable code is easy to write, easy to debug, and easy to maintain. Everybody wins!
Brent P. Newhall
Accountability Developer: www.other-space.com/stun/accountability/
Official comp.sys.be.help FAQ Maintainer: www.other-space.com/be/faq.txt
Personal homepage: www.other-space.com/brent/
Brent P. Newhall's publishing credits include The Washington Times, Computer Game Review, and an upcoming story in PC World. He has also been very active in the gaming community on the internet, including work on several raycasting engines.