Code Virtues, part 4: Testability
August 23, 2007 – 6:11 pmAnother day, another special virtue. We’ve seen the essential virtue and the meta virtue already. Today, we examine the epistemological virtue: Testability.
For everyone who never took a philosophy class, epistemology is the study of knowledge. Epistemologists wonder about things like whether having a justified true belief is sufficient (or even necessary) to actually know something, and can generally confuse just about anyone they meet should they so desire. (We’ll only be touching that realm lightly today, but if you’re interested drop me a note in the comments and I’ll point you at some good intro texts.) For our purposes, the virtue of testability is epistemological inasmuch as it tells us how correct our code is.
See, it’s one thing to run through our site in a browser, fail to observe any 404s or 500s, and proclaim our code correct. It’s an entirely different thing to know that no matter what edge case comes its way, our code can handle itself with dignity - and the only way to know that is to test.
If you’re not testing now - both unit and functional (and integration, but I feel hypocritical adding that, because that’s the one area where we’re lagging behind) - you should be. If you are testing now, keep it up and get better at it. The better tested your code is, the easier you can sleep at night.
You can make testing easier or harder by the way you write your code. If you have methods that run on for pages and have too many side-effects to count, you’re going to have some trouble testing it. If, on the other hand, you keep your methods small and modular, you’ll be able to test more easily. Testability is a natural outgrowth of things like test-driven development, but you can also write testable code without having the tests already written if you keep that target in mind.
Some guidelines for writing testable code are:
- Keep methods short and focused - one task to a method
- Group related functionality together, splitting it out into a new class when needed
- Minimize dependencies - they make testing much harder, even with the help of mocks and stubs
- Refactor when possible (this both supports and allows testing)
Next time, we’ll take a look at what might be the most controversial of the virtues: cleverness. Until then, excelsior!

