Monday, August 15, 2011

Why use factories?

I'd often heard / seen people using factories in programming. I never really understood the point of having a whole new class just for allocating/creating objects.

There is no reason to have only one factory class. The thing I missed is that the usefulness is obvious once you have two: one real one, and one that makes fake objects for testing the code that relies on the created objects. This allows easily injecting test objects into your tangle of production code/logic without changing the production code.

To really make this work, writing really testable code requires that you use a factory to create almost every object, and that factory might make real objects or test ones. This is the thing that requires constant effort / attention.

(You also don't need a different factory for each class. One for short-lived objects and one for long-lived ones is probably enough.)

No comments: