The situation. I have a class, Edc, that has an interface:


It needs to be composed with one of a few data lookup methods. Like a method connecting to SQL or a method connecting to XML.  I don’t want the caller to have to configure this finder object with the data method.  I’d like to make it easier.  Especially since this finder object is already being injected into another class as a pluggable object.

So, logically, move the construction of the finder to a factory method and compose the data method with it then.  I created a Factory class:

class EdcFinderFactory

But then, we have another class doing work.  So, with TDD, I switched the interface to an abstract class thinking I could use inheritance to mark all subclasses with a private constructor as well – and made the tests pass.  Good.

I was feeling OK about how things were going, but not thrilled.  I had working code but something smelled.  I realized something: there is only one class implementing IEdcFinder and that is EdcFinder.  Let’s remove duplication.

Remove: EdcFinderFactory
Remove: IEdc

(There were actually many small steps in here making sure the system still passed.)

Left with:

public EdcFinder(){..}
public Create(){…inside here we create an EdcFinder composed with IReadSomeData}

So, EdcFinder became a simple concrete class with it’s public constructor and the factory method.  And, as always, I ran the tests: Pass.  Then the constructor was marked private. Pass.  Remove the old abstract class (which was an interface to start with).

Now there was less code, less interfaces and easier to read code.  I was able to implement the “Replace Constructor with Factory Method” refactoring in just minutes and I know everything still works.

With TDD and my test suites I could change with out fear.

And two days later, I looked again  and removed this entire class realizing it was unnecessary and the data method could be simplified with Func<T>.  I switched everything in about an hour. Red, Green, Refactor.