Testing and Refactoring your code

Submitted by Tyler on Sat, 02/17/2018 - 14:18
Programming languages

I believe one of the core competencies of a good developer has to be writing tests for the code they write. I've only recently begun the practice myself, but have already made several improvements in the projects I have been apart of. The two hardest bits of implementing a Test Driven Development flow in my opinion are: on-boarding the practice, and continuing with the practice.

To tackle the first problem - on-boarding the practice of TDD a few things have to be done first.

  • Your team must be aware of the changes that are coming down the line and
  • the client must also be notified.

The client bit can be tricky. It helps to explain the many benefits of adopting this strategy, and that the pros of this style will be immediately apparent as the new code you write will have way less QA overhead, and will be more future-proof. After adopting a TDD approach the developer will have more confidence in the code, and fixing bugs will allow for an opportunity to strengthen the code base. 

On-boarding your teammates will be difficult at first. However testing code is a skill that will translate to any type of project, in any programming language. After a few tests, it will get easier and easier, and eventually there won't be a noticeable time difference in tested code vs untested code. Tests are beneficial because they allow you to think out how things are going to work, and will provide you with immediate feedback. Simply supply some training time to go over the testing framework for your project, and implement the methodology in small, easy areas first. Gradually move on to more complex areas of code, and force new code to have tests associated.

One way we have been facing the issue of continuous testing is by not accepting code that does not have tests associated with whats been written. Also, having a CI pipeline that automatically runs your tests is extremely helpful. We're currently using CircleCi for our project, but have also used Gitlab's pipelines to achieve the same effect. These pipelines will fail when a test fails, and if configured, will not allow the code to be pushed until the tests have been fixed. This is a great way to ensure that no new code will break existing flows.

After a few tests have been written, you will begin to see areas of your code that you can improve and refactor. This is because testing highlights duplication in your code. Because duplication is bad, you can write a test that refactors the evil code out. This is not my idea, and has been mentioned in many different books referencing clean code, and testing code.

I encourage all developers to asses whether or not they can start implementing tests in their code. The initial jump can seem scary, but once they take the plunge fixing and writing these tests can be exciting. Plus who doesn't like to see that green line appear after every successful test.