Saturday, 13 December 2014

Factory Obsession

I have noticed a pattern over the years with developers of which I will refer to as factory obsession. Everything is a factory or builder object. To some, the use of new is banned.


Consider a object that is responsible for some business logic and finally saves the result to a persistent store.

Message here is a value object, however the new can cause an odd fear within developers. Therefore a factory is required. Or is it? How can we test the repository is updated with the new message without reference equality?

An example test in C#, using the Mock framework with this newly introduced factory would look like:

This fear of new is wrong.

  • Instantiating value types is a good thing.
  • Instantiating entities is a good thing.
  • Instantiating services can depend - if the service is expensive we don't want to create lots of instances on a whim.

Here the factory offers nothing but a more strongly coupled solution.

If we ignore the factory the test becomes easier to write. To do this equality should be correctly implemented upon the message value type. I have questioned this in the past but for correct Domain Driven Design (DDD) semantics this is a good thing to follow.

We can take this further though. If we ditch the factory idea all together and replace the repository with a fake implementation we can have an even cleaner test fixture. You would still need equality but the design retains its flexibility.

Factories have their place, like all design patterns, however they should be introduced as part of the refactor step in most cases. Hiding the new keyword is not a goal. The fact that mocking frameworks default to reference equality shouldn't force you to make a more complicated or coupled solution to a problem.

No comments:

Post a Comment