The abuse of object factories

Recently I found this smell: the abuse of object factories.

Usually, there is already another smell: you are using DTOs.

Do not try to fake it removing "DTO" from the name. Instead, please read “Let the domain drive” architectural pattern and save yourself from a life of dumb conversions
You need to create it with some domain objects involved.
And... now... you have an object factory.

I rarely use object factories, because usually the constructors or a factory method are enough.
I use these rules:

  • if I am creating an object at the edge of the hexagonal architecture and I realise that I need to create it just "manipulating data" from other domain objects (and again... lots of smells here), a factory method or a constructor should be enough.
    Then, if a test gives me the feedback that I cannot proceed with that solution(*), I'll move to an Abstract Factory design pattern (or a more simple object factory)
  • if I am creating an object at the same level(**) of others needed to create it, sometimes I use the previous rule, while sometimes I ask to one of those objects to transform itself in the one I need (such as Java does with that toString)
I know that this is a basic/simple topic, but it can reduce significantly the number of objects in your application. Recently, applying this "tecnique", we reduced the number of objects in a package from 13 to 8. Not a big improvement, but the code is definitely more simple to read and change.

(*) for example, due to the number of collaborators involved, etc…
(**) "same level" means that you have all domain objects or all objects at the edge of the hex arch

Comments

Popular posts from this blog

First Experience, Then Words

Management and power