When should i use a factory method instead of a constructor?
#1
I’m trying to understand when it makes sense to use a factory method instead of just calling a constructor directly in my code. I keep reading that it helps with encapsulation, but in my current project, adding a separate method for object creation just feels like extra boilerplate without a clear benefit.
Reply
#2
We added a small factory to construct User objects from a DTO. It came in handy when the creation path changed later—like swapping in a different parsing rule or adding a cache—so the rest of the code didn’t have to touch the details. Without that, I felt the constructor was getting too fat.
Reply
#3
Most days I just call the constructor. Unless I need a different subclass or centralized validation, it feels like boilerplate to introduce a factory just for that.
Reply
#4
I tried using a factory when there were several shapes of the same interface and the consumer shouldn’t care which one it is. It helped in tests at first, but then you end up mocking the factory and that adds indirection.
Reply
#5
Is the real issue the complexity of the constructor or the desire for a clean API, and are we solving the wrong problem by introducing a pattern just to hide what’s already in the class?
Reply


[-]
Quick Reply
Message
Type your reply to this message here.

Image Verification
Please enter the text contained within the image into the text box below it. This process is used to prevent automated spam bots.
Image Verification
(case insensitive)

Forum Jump: