When I was writing last week's post I also thought about how TDD (or rather BDD) has helped me to early detect violations of the single responsibility principle.
I typically use classical BDD (Behavior Driven Development) style when naming my unit tests; Given_Foo_When_Bar_Then_Cowabunga. What I have seen is that this approach helps me to early identify classes that do more than one thing.
What happens is that the test name (or behavior description if you'd rather use that term) becomes ridiculous. Either the setup (the Given part) becomes very long or the observation (the Then part) becomes long. The latter is however not always a problem. When testing certain classes I find it natural to let the Given and When parts be part of the class name and then I have multiple Then methods to observe different parts of the behavior.
On occasion the When part becomes really long which is a warning sign since it means several related steps are required in order for me to test what I want to test. This is not always a problem but definitely a warning sign.
But whenever the Given part is huge I almost always end up splitting the class up in multiple classes. And interestingly enough I typically see the test name being one of the first indicators that something is wrong; the class is doing to many things or is too tightly coupled to something else.
Post a Comment