A decade of factories

I was reminded the other day that I have changed my mind about factories many times over the last few years.

First I started using factories a lot since VB4 didn't have parameterized constructors.

Shortly after I found out how sensitive the creational code was when writing MTS components. I more or less avoided the problem of, say, creating multiple transactions instead of one by accident. Factories were a good thing as there would be no New() and CreateObject() calls by mistake, only CreateInstance().

When COM+ came with Windows 2000, most of that problem went away - at least CreateObject() was fine, but there were still issues with New() in some situations... Anyway, I had COM+ projects where I decided not to force the usage of factories.

One thing I have liked with factories for a long time has been that they can configure the instance the way it should be and the consumer doesn't have to know about it at all. The factories (especially if they are interface-based) can even decide on which class to instantiate for the consumer. Then I found out that when using Test-Driven Development (TDD) it's a good idea to let the consumer be in control of configuration. That was a reason for using fewer (or at least pretty different) factories.

When I started working on the framework that is now known as Valhalla, I decided that the simplest and least intrusive way of instantiating entities was to just use New() and until factories were really necessary, I didn't use them. Then it occurred to me that I'm kind of violating the Single Responsibility Principle (SRP) when I have my creational code in the class itself. Eric Evans' book Domain-Driven Design was a good reminder of that. He uses a very good metaphor of a car engine. The car engine doesn't know itself how it is created, that's not its responsibility. This argument is especially valid in cases where the creational code is complex. OK, what's the moral of the story? I have no idea.
:-)
Well, it might be that you can't just decide to always use factories or always skip using them. As for everything else, it depends. It's good to be reminded about that every now and then.