October 3, 2007
10 Tips for Writing Code for People not Computers
In a recent article from Visual Studio Magazine, Rod Stephens wrote an article on how to write better code for yourself as well as other people who may view it. These tips can be applied to almost any programming language (JavaScript, .NET, PHP, etc.) so it is useful for any web developer.
"A computer does exactly what the code tells it to do and doesn't care what the code looks like. At the same time, it's easy to forget that you write code for people, not computers. Ultimately, you are satisfying the requirements of a user somewhere, not just writing text that will execute in a vacuum. In a development environment of any size, the code you write will be reviewed and or maintained by other people, so you need to make sure that you are clear about your intentions."
1. Use an abundance of comments to explain what the code is doing and why. The reader should never need to guess what the code is doing. Debugging code should be a simple matter of comparing the code's purpose to its behavior.
2. Use good variable names. Use Hungarian notation if required, but make the rest of hte name meaningful.
3. Use constants or enumerated types instead of magic numbers and hard-coded strings. The best part about this approach: It's another way for you to incorporate free comments.
4. Plan before you code. Many developers just sit down and start typing, but it's always better to at least sketch out a design before you code. Designing and programming can help you think about code in two different ways, essentially giving you two perspectives on the code.
5. Make sure code lines up nicely to show its structure. Your IDE helps but it can still do some weird things, particularly on continued lines.
6. Avoid sneaky tricks. If you need to use a complicated piece of code, comment it throughly.
7. Make routines small and with a well-defined purpose. If you can't describe a routine's purpose in one or two statements, break it up into smaller pieces. Keeping routines compact and discrete makes it easier to return to the code later and make adjustments.
8. Keep lines of code small enough to read without scrolling far to the right. If a line is too long, continue it on the next line.
9. Limit variable scope. The more limited a variable's scope, the easier it is to see what it is doing.
10. Minimize side effects. Routines that modify their parameters can be extremely confusing because the change is not obvious from the outside. Modify parameters as seldom as possible, and use comments to make it obvious whenever you do so.
