One Line Ata Time

When writing complicated code, or using an unfamiliar programming language or API, I will often write and test one line of code at a time. In other words, I do this:

  1. Write the UnitTest and enough scaffolding to verify that the test fails.
  2. Write one line of code.
  3. Compile and run the test.
  4. Verify that the test has failed exactly as expected.
  5. Return to step 2
When developing code this way, I always know exactly which line is leading to unexpected behavior, and I can fix it before writing more code that will obscure the problem. I tend to do a lot of internal refactoring as I add each line, so the final result is often better than what I do when I just whip out an entire function in one swoop, test it, and then move on.

I also tend to learn a lot about the system and API this way. I find undocumented return codes and exceptions. I discover interesting undocumented behavior.

It is important to have some means to examine the details of the error; a simple Pass/Fail indication is not enough at this level of granularity. This technique is especially valuable when using an environment such as Smalltalk, Java, or DotNet that can provide detailed exception information and a stack walk upon failure. It can also be useful to step through the lines with a debugger.

A similar technique works when debugging code: comment out the entire body of the function, and then restore lines one at a time until something unexpected occurs. (Sometimes a BinaryChop is more effective than full chop.)

Obviously, this technique can be time-consuming, especially if the unit tests are not automated or take a large amount of time. I don't do it all the time, but whenever I do it, I never feel that I've wasted any time.


CategoryTesting CategoryDebugging


EditText of this page (last edited September 22, 2002) or FindPage with title or text search