Rob Smyth

Tuesday 14 August 2007

Private Methods Can Be A Smell

When using TDD we write tests that give us a reason to write the production code we believe we need. The end result is that we end up with executable code specifications and an inherent 100% code coverage. But, if we find ourselves refactoring the code into private members for reuse then doesn't that mean that we have some duplicate test? That is, the same functionality is required by more than one public method.

This is not always the case, we could be calling the private method multiple times from the one public method. But if there are multiple public methods calling it then doesn't that mean that the tests on each of those public methods must each test all aspects of the private member? Duplication which is a smell.

The smell is that probably the tests for the following public methods are assuming that the first method's test test the private functionality. But this assumes that the code is not going to change (he he). So, I'm thinking that private methods that are invoked by calls to multiple public methods are a stench and ought not be allowed. In such cases refactor the code to extract the private method as a separate class or find a way to use one public method only.

Is this also a good example of why unit tests ought only test public behaviour. I'm wondering if the UT code was in the same assembly the private methods would be implemented as 'internal' or 'protected' methods and tested directly. I can see the attraction but it means that embedded classes remain hidden. The advantage of TDD in highlighting such cases is diminished.

I wonder if somebody has written a tool to detect such a code smell?

Links:

1 comment:

Nigel Thorne said...

Good to see you blogging Rob.
For my take on this see here.