Group Group Group Group Group Group Group Group Group

Why factory classes should be stateless


In the Objects & dependencies chapter, the factory based DI approach says that the factory classes should be stateless. Can you please explain the reason.

hi @karthickr,

:+1:, we incorporated the factories approach as stateless so that we could ease readers into learning dependency containers. Managing long lived dependencies adds complexity that we wanted to defer addressing until the dependency containers approach section. Since singletons and long lived objects are common in iOS development most apps would benefit from taking the dependency container approach.

However, if you have a correlated set of dependencies that are ephemeral, it could be useful to organize their instantiations within a stateless factory class. The nice thing about stateless factory classes is that they can be instantiated whenever needed. Unlike dependency containers which we have to carefully manage their instances and references to them.

Hope this helps. Let me know if you have any questions or if you have any feedback on the book in general.