Monday, January 9, 2012

Unit Tests, Code Quality and Legacy Code

Some days you start adding unit tests to legacy code. Perhaps you are about to make some changes, and you'd like to be sure you don't break something else.

In your Test Setup, you find that first you need to set this, and you need to call that, and you need to make sure this data is set, and so on.

There's a number of problems here, but the one that I'm looking at in particular is that as you continue to try to get your tests to run, you find more and more prerequisites.

Suddenly your Test Setup is starting to get a little out of hand.

This comes down to code quality.

What is good quality code? It's fairly complex to define. As you try to add a "second client" to a given class, you find out if it's easy to have someone else use the code or not. In this case our second client is the Unit Tests.

Fair enough, if the code is doing something complex, there may be a lot of setup, but there are two problems here.
  • It's not clear what setup is required.
  • Perhaps the code should not be doing something so complex.
Of course TDD gets around this by writing the tests first, and many of the things that we consider "good quality" come from the constraints that Unit Testing forces on you.

In this same way, unit testing make code reviews more practical. Now you have a Clearer Metric for good code. If the code can't be tested, it's a good hint that the code is not Good Code.

Before Structured Unit Tests, you had the pantomime code reviews -

  • "that functions too long", 
  • "oh no it's not", 
  • "oh yes it is" 
Now it's simpler

  • "that functions too long", 
  • "oh no it's not", 
  • "How come it's got no unit tests"
  • "it's doing too many thing to test"
  • "so it's to long then"
  • "yes, I guess so"
A lot of the Code Quality which people used to call subjective, now has a practical metric. If it's hard to write unit tests for, then the code's not good code.


No comments:

Post a Comment