Search code examples
oopfactory-pattern

Is it considered bad practice to use a static method as a factory?


I see most projects creating separate factory classes, so for example, they'll have a User class, and a UserFactory class. This makes sense if your factory needs more methods than just a CreateUser method, but most of these factories only have a constructor and a CreateUser method (or equivalent for whatever the factory creates). So, are there other reasons why you would create a separate factory class over just adding a static User.create() method to classes?


Solution

  • In my experience, separate factory classes are mainly used if you often want to change the implementation, especially for test cases. For example, if User has methods that hit a database and are "too slow" for a Unit Test, you might want to have a MockUser that doesn't use the database. Then you can have a RealUserFactory for the actual app, and a MockUserFactory for the unit tests.

    But there may be real world examples where you want to change, say from a SecurityClearedUser in your military spec app to a AnyOldUser in another. So a config file would declare the class of the factory, e.g. a MilitaryUserFactory or an AnyOldFactory.

    Of course, User.create() could read the actual class to create from a config file. So, in practice, I'm not sure if there's that much of a difference. Depends on how things are setup.