Excercise your APIs [www.oreillynet.com]

Curtis Poe says
"Here’s a little secret that many “test-infected” developers know: testing makes you a better programmer. It’s not just that your code works. It’s that if you find something is hard to test, that’s a code smell. Maybe your superWunderFunction() which takes 13 arguments isn’t designed terribly well. That’s not saying that all hard-to-test code has a design flaw (GUIs, for example), but as you test more, you start writing code that’s easier to test.

Your functions will take fewer arguments. Your functions won’t try to do too many things. Your functions are more likely to be loosely coupled. You’ll have less reliance on global variables. The list goes on and on.

When you start writing code that is easier to test, do you know what you’re doing? You’re eating your own dog food. You’re using your code and you start writing code which is easier to use. It starts becoming better-designed code. As an added benefit, if programmers are unsure how to use your code, they can always read the tests. Tests are not a substitute for documentation, but they are an excellent supplement to it."

This is the same thing I have noticed when I write tests. It really helps if you write the tests while you design the API, but even writing tests after the code is written will quickly reveal places where your code is less flexible and even hard to understand.

Writing a test makes you think about how the code will be used, and that helps you design an API that reveals its use more clearly, and has fewer unexpected side-effects. As an added bonus, you can reuse the tests and gain confidence tha your code does what you think it does, and catch interactions between different subsystems that affect each other.

Add comment