For every person, there are things they like and things they don’t. One such thing for me is testing my code. Is it laziness? Is it the fact that I’m awful at it? I’m not particularly sure why but in “5 Reasons why you should test your code” by Frank van Wijk, he talks about five important reasons on why we should always test our code.
Reason number one: Regression testing. The example he gives is that your code is fully functional and working but then one feature breaks in your code and now you’re left staring blankly at your code. Given that if you have 100% code coverage, you know there is a fully functional test suite. For example, you run the test suite, then you modify some parts of your code and then you run the test suite again. Now if tests are failing after the modification, there is an assertion done for this case. This is good because after every modification or as your program becomes more dense you could repeat this process each time to get rid of newly formed bugs.
Reason number two: Improve the implementation via new insights. After you finish your writing your program the first thing you might want to do is walk away grab a beer and reward yourself but before doing so you should write start writing tests for your methods. If you find that it is difficult to write tests for your methods then in may be an indication that there is room for improvement in the way you wrote your methods.
Reason number three: It saves you time. Although it takes up a huge chunk of your day writing tests for your code, in the long run it would actually save you time. The reason being, if you refactored your code, your tests should catch most of the bugs and allow you to fix it without having to sift through the entire program searching for what went wrong.
Reason number four: Self-updating documentation. There are many ways to understand code; read comments, read the implementation, or by reading the tests. It serves as a type of documentation that allows the reader to know what is suppose to happen.
And the final reason Wijk gives is because it is fun.
For the most part I found this blog quite fun to read because the author made a few valid points. Writing tests may be a pain but in the end it does make you a better programmer and ensures that there is less room for errors. I know my biggest weakness is testing my code because I never have in the past and moving forward I will start to.
Thank you for the read!
From the blog CS@Worcester – Life in the Field of Computer Science by iharrynguyen and used with permission of the author. All other rights reserved by the author.