How I test code

This post is inspired by a great piece by Rails creator DHH.


My name is Dan, and sometimes I write tests first, and sometimes I write tests afterwards, and sometimes I don’t test at all because it would add brittleness for no benefit. Often I delete tests that I think have outlived their usefulness, or add in tests when I find a crucial piece of code broke without warning.

I sometimes use tests to guide design, then throw the whole implementation away (tests and all) because the design was wrong — and it was the tests that told me so.

I only write tests when they allow me to go faster, further, with more focus and with more confidence. Sometimes I use this for prototyping, but not always – it depends on to what degree I’m prototyping code structure (TDD is great!) vs integration (TDD sucks!).

I try to remember that every line of code I write is a line that must be maintained, and that includes tests. I believe in lean code, AND lean testing. I believe that over thousands of iterations we can trim our implementations AND our tests down to just what is needed.

Also, when I write code…

Sometimes I rush headlong into the codebase and put in a giant refactor because some anti-pattern totally infuriates me. This is probably (but not certainly) my worst habit. But sometimes it’s been a giant win, even if it results in near-term instability.

I believe in sitting back and reading code I haven’t looked at in a while just to ask “am I proud of this, or could it be better?” because it’s a good way to bring fresh eyes to the design, and then making a small improvement and moving on.

I also believe that it’s ok if the first pass of anything isn’t perfect, because as long as someone is re-entering the code and making it a little better, it’ll get where it needs to go.