I know this topic has been discussed a lot already so I don't want to get into which one is the "best way".
I have been using field injection for a couple of years now but recently I discovered that many people prefer constructor injection because the collaborators of a class have to be explicitly set before you can create an instance of a class.
One argument to use constructor injection is that it makes you think about how many classes you are actually depending on. I have been looking over the classes in one of my projects to see if I have too many dependencies.
I noticed a class of mine had about 6 dependencies, when I provide them via the constructor I get a really ugly constructor. This makes me think I may be depending on too much here.
When I think about it however, I don't think it makes sense in this case to split up the class in smaller ones.
The case is this:
There is a service class with one method "createContract" that takes input from a form and makes a contract with the provided data.
The form has 5 dropdowns in which you choose certain codes / types for that contract. Each one corresponds with a separate entity stored in another database table.
class FormData {
private String aFieldOnTheContract
private String fictiveCode1Id;
private String fictiveCode2Id;
private String fictiveCode3Id;
private String fictiveCode4Id;
private String fictiveCode5Id;
}
Later in the service when I want to create this contract I use 5 "XyzRepository" classes to look up the entity by the id of the one you have selected in the form.
I'm not sure how I could change my design to not have to do this and be able to remove these 5 dependencies. Any ideas?