How to Program

I can hear your thoughts.  You're thinking, "I already know how to program."  Of course  you do, or you wouldn't be reading this.  But bear with me, because what follows will make you a better programmer.

First, design, design, design.  Think through exactly what you want the program to do, even if the requirements are spelled out in a class assignment.  Make sure your classes do only one thing, and do it well.  Make your functions even more specific.  Don't expose private methods or properties.  Of course.

Second, when you write a function, go over it line by line before you ever compile your program.  Among other things, do the following:

  • Make sure the function has only one way to return.
  • Make sure, if you have opened a file, you have closed it.
  • Look at each loop, each statement, and make sure it does what you want.  Make sure the loop can terminate.
  • If a statement can cause an error, make sure you have try/catch blocks.
  • If you use variables in a loop, make sure you have initialized them outside of it.
This can be surprisingly hard while you're actually writing the code.

Third is the "yellow pad" technique.  Get a scratch pad and a pen, then do the following:

  1. Bring up your program with the debugger and start testing each feature.  Be methodical.  Test one part thoroughly before going on to the next.
  2. As you encounter a problem, write it on the yellow pad.  I usually number the problems.
  3. Find as many problems as you can, using the debugger to get around issues so you don't have to recompile to keep testing.
  4. Once you hit a point where you can't keep testing, or you have more than 10 problems, stop, fix each one, and put a checkmark next to it to indicate that you think you fixed it.
  5. Test again to make sure you actually fixed everything.  As you determine that a problem has been fixed, cross it off your list.  If it isn't fixed, leave it.  As you find new problems, add them to the end of the list.
  6. Repeat the process until you cannot find any problems.

The preceding points and the following observations are based upon years of writing production code.  I'm not pretending that these originated with me; you can find them in most software engineering books.  They're common sense.

  • The cost of fixing a problem increases dramatically with the time elapsed after writing the original code.  Not having a bug in the first place, by designing well and checking your code, is best.
  • Every time you edit a program, you risk introducing more bugs.  Thus limit the number of times you need to edit.
  • Usually, it costs, in terms of time, very little more to fix two problems than to fix just one during an editing session.