Dagger 2; Dealing with long constructor arguments

196 views
Skip to first unread message

Alex Fu

unread,
Dec 6, 2016, 7:56:11 AM12/6/16
to Dagger Discuss
I'm curious about what others (if any) has done about long constructor arguments when dealing with constructor injections. I've got some objects with around 10 arguments in the constructor and it's starting to get out of hand. Has anyone dealt with this or is this mostly a non-issue? I thought about treating the arguments as a value type and using AutoValue to create a "Constructor" object that would hold the arguments to my class. The only downside is, I would need to provide the "Constructor" object manually.

Thomas Broyer

unread,
Dec 6, 2016, 8:48:08 AM12/6/16
to Dagger Discuss

On Tuesday, December 6, 2016 at 1:56:11 PM UTC+1, Alex Fu wrote:
I'm curious about what others (if any) has done about long constructor arguments when dealing with constructor injections. I've got some objects with around 10 arguments in the constructor and it's starting to get out of hand. Has anyone dealt with this or is this mostly a non-issue? I thought about treating the arguments as a value type and using AutoValue to create a "Constructor" object that would hold the arguments to my class. The only downside is, I would need to provide the "Constructor" object manually.

It might be a case where your class does too much [1] and some things would benefit from being factored out into other classes.
IMO, passing a "context" object instead of the actually dependencies would only be trying to hide the problem under the carpet [2].

Christian Gruber

unread,
Dec 6, 2016, 12:15:36 PM12/6/16
to Dagger Discuss
Yep. Generally, I find that long constructors are a symptom of classes having too many responsibilities.  The exception being those classes whose purpose is to switch between a variety of codepaths, essentially dispatching to other collaborators.  In such situations, however, it's worth looking to see if you really have a situation that could be appropriately handled with a mapbinding or setbinding.

I've seen "Config" options whose entire job is to shorten constructors, but generally I regard this as pushing the problem around, not solving it, because the problem isn't hard-to-read code - that's just the symptom.

C.

--
You received this message because you are subscribed to the Google Groups "Dagger Discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email to dagger-discus...@googlegroups.com.
To post to this group, send email to dagger-...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages