Writing tests in hindsight is like writing no tests at all

Silvester van der Bijl
16 October 2018

We frequently encounter teams that have to deal with complex and fragile codebases. Almost all of these teams are fully aware that the quality and robustness of the code is one of their main problems but they’re struggling to find the right answer.

One approach I’ve seen teams attempt (and have actually tried myself) is to attempt to write tests for the existing codebase. While valiant, this approach will most likely get you nowhere. Here’s why:

  • Test Driven Development and unit testing is not just about validating behaviour, inputs and outputs but it forces you to think about the design of your classes, functions and methods. Writing tests in hindsight reverses this principle. You design tests around your existing code. You’re trying to reproduce the thought patterns of the multiple developers that came before you.
  • Legacy codebases tend to be relatively large. A team can spend months writing tests for many parts of the system only to discover the overall code coverage has gone up from 0,01% to 10%. Would you refactor without fear on a system with just 10% code coverage?
  • Best case scenario you’ve successfully managed to test all paths into some arcane piece of code. Are you sure this code is being used in production? Has it ever caused problems? Will the functionality change anytime soon?
  • This process is time consuming. You’re probably better off spending precious development capacity into delivering new (properly tested) features to your users.

How can you increase quality

Writings tests and applying Test Driven Development is a good start! Just apply common sense and don’t go overboard with writing tests for your existing codebase. Where your code branches off into untested code perhaps apply an interface you can test. It’s probably also a good idea to add a test that validates the behaviour you’re expecting from the new code’s perspective but don’t drill down.

If you can’t make heads or tails from existing code then don’t try. Instead rebuild the feature the code is supporting using the help from domain experts, customers, users, etc. Make sure to apply TDD this time though ;-)

Summary

Proper testing is essential for keeping quality of a system high. High quality is the only way to be able to move fast but don’t assume adding tests for existing code will reap the same benefits.

Want to know more about dealing with legacy codebases? Send me a message on LinkedIn or just ask in the comments!

Subscribe by Email