Search This Blog

Tuesday, May 11, 2010

How does TDD affect design

I have heard many times the claim that you should try TDD because it helps you improve the design of your code. In fact many people claim the design benefit is more important the benefit you get from having an automated regression suite. However I have never been able to pin down how TDD helps your design. Reading Growing Objected-Oriented Code Guided by Tests I saw the first explanation of how TDD can actually improve design.


Thorough unit testing helps us improve the internal quality because, to be tested, a unit has to be structured to run outside the system in a test fixture. A unit test for an object needs to create the object, provide its dependencies, interact with it, and check that it behaved as expected. So, for a class to be easy to unit test,
the class must have explicit dependencies that can easily be substituted and clear responsibilities that can easily be invoked and verified. In software engineering terms, that means that the code must be loosely coupled and highly cohesive—in other words, well-designed.
When we’ve got this wrong—when a class, for example, is tightly coupled to distant parts of the system, has implicit dependencies, or has too many or unclear responsibilities—we find unit tests difficult to write or understand, so writing a test first gives us valuable, immediate feedback about our design. Like everyone, we’re tempted not to write tests when our code makes it difficult, but we try to resist. We use such difficulties as an opportunity to investigate why the test is hard to write and refactor the code to improve its structure. We call this “listening
to the tests”


So admittedly I don't think I understand all of this, but it gives me hope that the book will teach me more about these ideas as I go and I will learn to build better designs.

1 comment:

  1. I like Uncle Bob's term "conveniently callable" to describe the result of code written while using TDD.

    ReplyDelete