Reducing coupling through unit tests 2008-05-22


After my previous post on the subject of coupling and cohesion, a lot of the feedback I've gotten has been from people who want examples of lowering coupling, or want to know how they can see if their code is loosely coupled. The easiest way I know of doing that also has other benefits: Whether you prefer Behavior Driven Development or test driven development, or you call it something completely different, writing unit tests provide you with one or two essential things:

How unit testing help reduce and/or measure coupling

The Wikipedia article on coupling provides this definition:
Low coupling refers to a relationship in which one module interacts with another module through a stable interface and does not need to be concerned with the other module's internal implementation.
The thing is, when you write unit tests, you are putting the unit being tested into a harness. You need it to interact with your test code, and still carry out its functions. If you write the tests upfront, you have two alternatives: Either you create a hugely complex harness with lots of mock objects, or you write your code in a way that makes it easy to call in isolation. That is another way of formulating low coupling: A module exhibits low coupling if it is easy to call in isolation. Unit testing under any name is a good test of the ability to call your code in isolation Testing after the fact gives you a measure of how well you have done: If you have written code with low coupling, it should be easy to unit test. If you have written code with high degrees of coupling, you're likely to be in for a world of pain as you try to shoehorn the code into your test harness. If you haven't bought into TDD/BDD for other reasons, consider it for this reason. Try it. The structure of your code will change if it wasn't previously loosely coupled, as you'll quickly tire of writing horrendously complicated tests.

Some indicators of the level of coupling

The last point highlight that looking just at coupling in isolation isn't all that helpful. But thankfully, if you strive to reduce coupling, one of the key things you end up doing a lot of the time is write more cohesive code. If you're constantly focused on ensuring code can be tested in isolation, there are few ways around that without making each module cohesive.

blog comments powered by Disqus