TDD and the Single Responsibility Principle

Listen to this post

I mentioned earlier that TDD offers qualitative measurements about production code, namely that a large average fixture size can be used to measure relative coupling in a system. Similarly, tests can reveal whether, and to the extent, that the Single Responsibility Principle has been adhered to.

The Single Responsibility Principle states that every class in a design should have a single responsibility. It is an aspect of cohesion in design. The reason that tests will reveal when this principle has been violated has to do with the number of tests needed for that class’ behavior.
For example, lets say a class is responsible for connection to an HTTP service, but also has to validate that the data returned adheres to a domain-specific language. Tests would have to be written that ensured the connection was made properly, and other tests that the DSL was accurately applied.

But because both behaviors exist in the same class, tests would also have to be written to ensure there were no side-effects between these behaviors: that the code that validates the DSL did not “step on” any state needed for the connection, and vice-versa.

Systems that violate the Single Responsibility Principle often see test packages that are far larger than the production code packages. This is because of these additional tests that are needed.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.