Bjarne Stroustrup, the creator of the C++ programming language, has a couple of famous quotes about testing.
"A program that has not been tested does not work."
"How to test? is a question that cannot be answered in general. "When to test?" however, does have a general answer: as early and as often as possible."
When you first write a piece of code how do you know it works? And more importantly how will you and the others you work with know that its still working in the future? The answer to both questions is tests, tests, tests.
When you write tests your performing several key functions.
Eating Your Own Dog Food
By writing tests your placing yourself in the shoes of the user, if this is combined with a TDD approach you'll be able to produce an API that feels intuitive and friendly right from the start.
An API should be written in a form that is of benefit to the user, not because it was easier for the developer that way or "Well that's just kind of the way it turned out"
Validating the Design
Writing the tests first means as you implement parts of the API and tests start passing your validating that your design is meeting the contract you've established with the user, once all the tests pass your API does what is says on the tin.
Importantly this shows the tests aren't passing by luck its because you implemented another piece of the jigsaw.
Documenting How This is Supposed Work
We all know sometimes code has to be refactored or modified, in large code bases with large teams its quite likely that this isn't being done by the person that first wrote the code, or that person only has a hazy recollection of writing that code.
By having a well tested piece code were enabling the developer to understand the consequences of the changes that are being made, no developer means to introduce bugs, they don't always jump off the screen, but failing tests highlight immediately that a particular change may not have been for the best or that it will have an impact on the API.
This documentation of expected behaviour that testing provides is critical, I often hear developers say "I only changed this small thing and now loads of tests are failing", this is a good thing, it proves the code was being tested and can often highlight that what was perceived as a small change actually has big consequences for the user of an API.
Making it Testable
Once again the SOLID design principles have our back, code written using these principles is easier to test, easier to design by TDD and will reap the benefits that both can give.
If your code isn't testable its a smell that the design is wrong,
Maybe it does more than one thing (SRP).
Maybe the tests break all the time because your constantly having to modify the code (OCP).
Maybe its to tightly coupled to its dependencies (DIP).
So next time someone shows you some untested code ask them "Yeah thats really nice, how do I know that works?"
No comments:
Post a Comment