To Field Inject or Constructor Inject

Here I outline the type of Injection technique you should typically choose for a given scenario. I assume you are already aware of what Dependency Injection is and what is Field Injection or Constructor Injection.

Field injection example:

package superclass;
public class SuperClass {
@Inject
HttpClient mHttpClient;

}

 

Constructor injection example:

public class SuperClass {
private final HttpClient mHttpClient;
@Inject
public SuperClass(HttpClient httpClient) {
mHttpClient = httpClient;
}
}

Field injection if you do not control the creation of an object. Examples are UI objects like Activities and Fragments in Android or ViewControllers in iOS development. If some framework is creating the object and then handles it to us then we have no option than injecting it after the creation.

Constructor injection if we control the creation of an object, like the business logic, managers, view models etc. Also we need constructor injection if the class is/may be used by other projects, in this case the project using our class could be using a different framework for dependency injection.

In case your constructor has lots of parameters, I personally do not prefer more than three parameters, it could indicate a clear violation of Single Responsibility Principle. You need to refactor your code either by applying Facade Structural Pattern or in some cases with Parameter Object.