Should I use a factory method or constructor for simple classes?
#1
I'm trying to understand when it's appropriate to use a factory method versus just calling a constructor directly in my code. I keep seeing both patterns used, but in my current project, I added a factory and now I'm wondering if it's just unnecessary abstraction for a class that isn't that complex.
Reply
#2
For a tiny class, the constructor is usually enough. The extra indirection can feel like ceremony and it can hide the fact you’re just building one object. I only reach for a wrapper when creation is non trivial or depends on environment.
Reply
#3
I did add a factory once, and it helped when I needed different concrete types behind the same interface or when construction involved several steps; for a simple class it was overkill.
Reply
#4
Are you sure the pain is in creation, not in wiring up dependencies or testing? sometimes the real bottleneck is elsewhere.
Reply
#5
I remember a sprint where we argued about this for a small service. I started with a wrapper around new, then dropped it as soon as deployment drifted and tests started failing to mock the wrapper. We measured unit test coverage and it didn’t move much, so we went back to direct constructors and kept the changes small.
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: