What makes good code?

Contrary to what many beginning programmers like to think, good code isn't simply about writing a program that does its job. Writing code well is an art that involves thoroughly understanding and decomposing the problem before sitting down at a keyboard.

I heartily recommend that everyone interested in writing good code, no matter what language you use, read Code Complete, by Steve McConnell. The quality of my code increased drastically once I read a few chapters of this book.

Good code is easy to understand.

When you sit down to write a program, chances are you have a sort of "flow". You understand the problem. You have the design of your code nicely in your head. You know exactly which code does what. It's easy to make the mistake of thinking that if you leave this code alone for a few months and come back to it, you will still be in that state. It's also easy to make the mistake of thinking that other people looking at your code will have a similar intuitive understanding of the problem and your program as you. However, unless you make a conscious effort to make your code easy to understand, neither of these things are going to be true.

How does one create easily understandable code?

Good code is grouped into managable pieces.

When you're building a house, e.g., you use planks, bricks, nails and so on. These are manageable pieces that you put together, and presto! A house! It would be quite hard to build a house if some planks came with nails already in them, on random places, and the bricks were all weird sizes.

Something like this is what makes up object-oriented programming. You create "planks", then "bricks", then "nails", then put it all together. You don't create the house all at once.

Good code has good comments, not necessarily lots of comments.

Here's something you don't hear enough of -- obsessively commenting everything is a terrible thing to do. Over the course of learning programming, you've almost certainly heard plenty of people tell you that your program needs to be commented. Few people will tell you how to make these comments worthwhile.

First of all, comments should explain the problem at a higher level than the code. The low-level, "this assigns 3.5 to x" meaning should be clear enough from your code. (Well-written code should already explain what's happening at a slightly higher level by using descriptive variable names. You should almost never use a raw "3.5" literal constant in code, instead giving it a descriptive constant name.)

What is good to do, when writing a new function, is to describe at a high level what the code does with comments first, then fill in the code. If you try to comment your code at a too low level one day your comment will be erroneous since you have changed the code, but not the comment.

SoftwareEngineering (last edited 2005-02-04 02:39:52 by Adam Chlipala)