Dane's Stuff

Testable Code is Good Code


I talked about testable code in another post. I wanted to expand on that and explain a bit more why testable code makes your code better.

Better code is a subjective term, so let me define a bit about what I mean. By better, I mean it's easier to read, easier to change, smaller methods and classes. Although these things don't necessarily make your code better, you can have these things and your code could still be bad, to me at least, they are things I strive for in my code.

How your tests interact with you code is your first feedback in how hard it is to use the code you are writing. If you (write the code you wish you had in your test)[https://spec.fm/podcasts/developer-tea/b122f924], you start actively designing the interface. Most times if your code is easy to test, its changeable, easy to read.

Again I say mostly, you could make a test library that makes it easy to test the code, or have some code that is just wrong. But if you are testing your code through the code interface and you have problems with you tests, or (code smells)[http://xunitpatterns.com/] it is a good indications that something is lacking in your code design. It could be the test are very big because it doesn't have a single responsibility, or its hard to test certain things because of side effects. Hopefully I will go into more detail in later posts. But whatever they are, those are feedback loops your test are giving you about your unit under test. If you listen to your tests as you write or change your code, many times it will greatly improve your code, or at least highlight some design flaws.